删除重复的2列排列

5
我找不到一个好的问题标题,请随意编辑它。
我有这个数据框。
  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”的重复行,而不计算2列的排列组合:例如(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来删除重复键,但我认为这是一种不优美的解决方案。以下是我的数据的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")

只是好奇:你的实际数据集有多大? - A5C1D2H2I1M1N2O1R2T1
@AnandaMahto 我的数据集不是很大(10000行)。 - agstudy
2个回答

4
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

此想法的出处来自这个问题:从数据帧中删除连续重复项,特别是@MatthewPlourde的回答。


+1 谢谢!因为你使用了一个干净的方法构建了密钥,比粘贴更好。 - agstudy

4
你可以尝试在apply函数中使用sort对组合进行排序。
mydf[!duplicated(t(apply(mydf[3:4], 1, sort))), ]
#   section time to from
# 1       a    9  1    2
# 3       a   12  2    3
# 4       a   12  2    4
# 6       a   12  3    4

谢谢!这就是我正在寻找的解决方案!您能否解释一下为什么要转置吗? - agstudy
@MatthewLundberg,使用我的方法可以通过使用“range”而不是“sort”来获得一些性能提升。例如,x <- apply(mydf[3:4], 1, range); mydf[!duplicated(x, MARGIN = 2), ]接近所需。不确定它如何扩展;) - A5C1D2H2I1M1N2O1R2T1
@AnandaMahto,能否请你编辑一下你的问题呢?因为我只有两列进行比较,所以我会尝试一下。我喜欢你的优雅解决方案,希望它能更快一些。 - agstudy
@agstudy,这种方法不会比Matthew的更快。由于使用了“交互”创建的底层因素,Matthew的方法很可能会扩展得更好。 - A5C1D2H2I1M1N2O1R2T1
@AnandaMahto 非常感谢您的关注!我的粘贴方法比Matthew的方法慢(比排序快),所以我认为您说的底层因素是正确的!我仍然是一个R新手,有很多东西要学习! - agstudy
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接