我有一个只有三列但有数千行的 data.frame
。第一列和第二列报告数字 ID,它们的组合表示一个链接(例如 A-B 等于 B-A)。
现在,我想删除所有与链接重复的行,选择第三列中具有最高值的行。
下面是一个简短的例子:
我的输入data.frame
:
1 2 100
102 100 20000
100 102 23131
10 19 124444
10 15 1244
19 10 1242
10 19 5635
2 1 666
1 2 33
100 110 23
我的目标是:
100 102 23131
10 19 124444
10 15 1244
2 1 666
100 110 23
我试图在 R
中找到解决方案,否则 postgreSQL
也可以。
非常感谢!
最佳答案
The idea is similar to this one .您可以使用 pmin
和 pmax
创建两个额外的列来分组,如下所示:
data.table
解决方案。但是如果你不想要data.table,那么你仍然可以使用这个想法。但是,您不太可能比仅使用 R 代码的 data.table 解决方案更快。
# assuming your data.frame is DF
require(data.table)
DT <- data.table(DF)
# get min of V1,V2 on one column and max on other (for grouping)
DT[, `:=`(id1=pmin(V1, V2), id2=pmax(V1, V2))]
# get max of V3
DT.OUT <- DT[, .SD[which.max(V3), ], by=list(id1, id2)]
# remove the id1 and id2 columns
DT.OUT[, c("id1", "id2") := NULL]
# V1 V2 V3
# 1: 2 1 666
# 2: 100 102 23131
# 3: 10 19 124444
# 4: 10 15 1244
# 5: 100 110 23
关于r - 检测前两列数字组合相同的行,选择第三列数字最大的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15495795/