且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过列值的排列在R中聚合

更新时间:2023-12-01 11:31:58

这里是一种解决方案:

library(dplyr)
df$pair <- ifelse(df$Destination < df$Origin,
                  paste(df$Destination, df$Origin, sep = ','),
                  paste(df$Origin, df$Destination, sep = ','))

df %>% group_by(pair) %>% summarise(Flow = paste(Flow, collapse = ' + '))

Source: local data frame [2 x 2]

   pair    Flow
  (chr)   (chr)
1   a,b f1 + f2
2   c,d f3 + f4

流量列为显然使用字符向量粘贴,因为这就是您给的。如果您有数值,则可以修改为 sum(Flow)

The Flow column is obviously paste using character vectors since that is what you gave. You can modify to sum(Flow) if you have numeric values.

编辑:对不起,我之前是汇总错误的列。固定。

EDITED: Sorry, earlier, I was summing wrong column. Fixed.