【发布时间】:2017-07-18 12:30:00
【问题描述】:
我需要删除组 (ID) 中两列(feedID 和 feedID2)的重复组合,同时在数据集中保留大量其他列。应删除所有重复的行,无论是第 2 列中的 A 和第 3 列中的 B,反之亦然。 此外,我想删除所有行,例如两列中都有 A,或者其中一列中有 NA。 我无法对列之间的数据进行排序,即如果 A 在第 nr 2 列中,它应该保留在第 nr 2 列中。
我知道这可能是一个重复的问题,但其他答案似乎都不适用于我的数据集,或者要求相同的问题。 例如。 Finding unique combinations irrespective of position Removing duplicate combinations in R (irrespective of order)
test <- data.frame(ID= c("49V", "49V","49V", "49V", "49V", "52V", "52V", "52V"),
feedID = c("A1", "A1", "G2", "A1", "G2", "B1", "D1", "D2" ),
feedID2 = c("A1", "G2", "A1", "G2", "NA", "D1", "D2", "NA" ))
desiredoutput <- data.frame(ID= c("49V", "52V", "52V"),
feedID = c("A1","B1", "D1" ),
feedID2 = c("G2", "D1", "D2" ))
如果在不同的列中,以下代码不会删除重复项
test2 <- test [!duplicated(test[,c("ID","feedID", "feedID2")]),]
这段代码什么都不做,但不会抛出任何错误
test2 <- test%>% distinct(1,2,3) # where numbers refer to the columns
此代码会产生一个错误,对于 dimnames,不确定这意味着什么。我的测试数据没有得到这个,我不确定为什么并且无法重现错误...
indx <- !duplicated(t(apply(test, 1, sort))) # finds non - duplicates in sorted rows
test[indx, ]
有什么想法吗?
【问题讨论】:
-
你试过
unique吗? -
我不明白你想用
ID列做什么。 -
Unique 仅保留选定的列,我需要保留所有列(47!)。 @头足类
-
对于每个 ID,我需要删除重复项。因此,如果 ID 1 和 2 具有相同的 feedID 组合,则不会被视为重复。只有在每个 ID 中,我才能删除重复项。 @AndrewBrēza
-
@Lisarv 好的,
nest然后使用unique和unnest应该可以完成这项工作.....nest的示例 stackoverflow.com/questions/44363535/…
标签: r duplicates