R 在前两列中检测具有相同数字组合的行,并在第三列中选择具有最高数字的行

R 在前两列中检测具有相同数字组合的行,并在第三列中选择具有最高数字的行,r,postgresql,dataframe,R,Postgresql,Dataframe,我有一个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 11

我有一个
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
也可以。 非常感谢

。您可以使用
pmin
pmax
创建两个附加列,以按如下方式分组:

A
数据表
解决方案。但是如果您不需要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
#假设您的data.frame是DF
要求(数据表)

DT这里有一个基本R选项,主要用于共享备选方案。因为它涉及到转置和排序,所以在“数千行”数据集上,它确实可能很慢。它假定您的
数据。帧
称为“mydf”:

postgresql中的myAggs

如果原始表是由三列整数(a、b、c)构成的,则可以使用条件函数建立max(a、b)、min(a、b)的唯一键:

然后,您可以使用“组”获得每个键(键1、键2)的最大C值:

Postgresql:

select distinct on (1, 2)
    least(a, b), greatest(a, b), c
from data_frame
order by 1, 2, c desc

伟大的我不知道这个包裹,它似乎非常适合我的情况!多谢各位!(+1)您应该注意,此处不保留订单。
select 
 case when a>=b then a else b end as key1, 
 case when a>=b then b else a end as key2,  
 c from table;
select 
 key1, 
 key2, 
 max(c) as max_c 
 from (
  select 
  case when a>=b then a else b end as key1, 
  case when a>=b then b else a end as key2,  
  c from table
 ) query
 group by key1, key2;
select distinct on (1, 2)
    least(a, b), greatest(a, b), c
from data_frame
order by 1, 2, c desc