【问题标题】:Remove duplicated 2 columns permutations删除重复的 2 列排列
【发布时间】:2012-12-14 05:59:54
【问题描述】:

我找不到这个问题的好标题,所以请随时编辑它。

我有这个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 的重复行,而不计算 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 删除重复的密钥,但我认为这是一个肮脏的解决方案。

这里是我的数据输入

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")

【问题讨论】:

  • 只是好奇:您的实际数据集有多大?
  • @AnandaMahto 我的数据集不是那么大(10000 行)。

标签: r duplicates dataframe


【解决方案1】:

您可以尝试在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

【讨论】:

  • 谢谢!这就是我正在寻找的解决方案!您能解释一下为什么要转置吗?
  • 在(小)示例中,我的速度提高了 2.5 倍(并且不使用 mn、mx 的变量)。
  • @agstudy,试试t(apply(mydf[3:4], 1, sort)) 并将其与apply(mydf[3:4], 1, sort) 进行比较,看看我为什么转置apply 的输出。
  • @MatthewLundberg!谢谢!你说得对!我对其进行了测试,我认为排序在这里很耗时!
  • @agstudy 将 sort 替换为 I。有趣的性能结果(当然是错误的输出)。
【解决方案2】:
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 的回答。

【讨论】:

  • +1 谢谢!因为您使用干净的方法构造密钥,比粘贴更好。
猜你喜欢
  • 2023-03-07
  • 2017-08-03
  • 2016-04-26
  • 2022-07-22
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
  • 2012-02-02
相关资源
最近更新 更多