R跨数据框列折叠重复对(以任何顺序)并编辑第3列?

R collapse duplicate pairs (in any order) across dataframe columns and edit 3rd column?

我使用 rbind 连接了 2 个数据帧,其中一列表示其来源,结果是

    from | to | source
1     A    B      X    
2     C    D      Y
3     B    A      Y
...

我想寻找重叠对,而不考虑“顺序”,合并这些对,然后将源列编辑为其他内容,例如"Z".

在上面的示例中,第 1 行和第 3 行将被标记为重叠,因此它们将被合并和修改。

所以期望的输出看起来像

    from | to | source
1     A    B      Z    
2     C    D      Y
...

如何做到这一点?

您可以试试下面的代码

unique(
  transform(
    transform(
      df,
      from = pmin(from, to),
      to = pmax(from, to)
    ),
    source = ave(source, from, to, FUN = function(x) ifelse(length(x) > 1, "Z", x))
  )
)

这给出了

  from to source
1    A  B      Z
2    C  D      Y

示例

set.seed(1)

df=data.frame(
  "from"=sample(LETTERS[1:4],10,replace=T),
  "to"=sample(LETTERS[1:4],10,replace=T),
  "source"=sample(c("X","Y"),10,replace=T)
)

   from to source
1     A  C      X
2     D  C      X
3     C  A      X
4     A  A      X
5     B  A      X
6     A  B      X
7     C  B      Y
8     C  B      X
9     B  B      X
10    B  C      Y

然后

tmp=t(
  apply(df,1,function(x){
    sort(x[1:2])
  })
)

t1=duplicated(tmp,fromLast=F)
t2=duplicated(tmp,fromLast=T)

df[t2,"source"]="Z"
df[!t1,]

  from to source
1    A  C      Z
2    D  C      X
4    A  A      X
5    B  A      Z
7    C  B      Z
9    B  B      X