我找不到这个问题的好标题,所以请随时编辑它。
我有这个 data.frame
section time to from
1 a 9 1 2
2 a 9 2 1
3 a 12 2 3
4 a 12 2 4
5 a 12 3 2
6 a 12 3 4
7 a 12 4 2
8 a 12 4 3
我想删除具有相同
to
的重复行和 from
同时,不计算两列的排列:例如 (1,2) 和 (2,1) 是重复的。所以最终输出将是:
section time to from
1 a 9 1 2
3 a 12 2 3
4 a 12 2 4
6 a 12 3 4
我通过构造一个新的列键有一个解决方案,例如
key <- paste(min(to,from),max(to,from))
并使用
duplicated
删除重复的 key ,但我认为这是肮脏的解决方案。这里是我的数据的 dput
structure(list(section = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), .Label = "a", class = "factor"), time = c(9L, 9L, 12L,
12L, 12L, 12L, 12L, 12L), to = c(1L, 2L, 2L, 2L, 3L, 3L, 4L,
4L), from = c(2L, 1L, 3L, 4L, 2L, 4L, 2L, 3L)), .Names = c("section",
"time", "to", "from"), row.names = c(NA, -8L), class = "data.frame")
最佳答案
mn <- pmin(s$to, s$from)
mx <- pmax(s$to, s$from)
int <- as.numeric(interaction(mn, mx))
s[match(unique(int), int),]
section time to from
1 a 9 1 2
3 a 12 2 3
4 a 12 2 4
6 a 12 3 4
这个想法归功于这个问题:Remove consecutive duplicates from dataframe尤其是@MatthewPlourde 的回答。
关于删除重复的 2 列排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14078507/