首页 > 解决方案 > 将两对列合并为具有唯一值的两列

问题描述

我有下面的数据框:

from<-c("Jack","Bill","Jack","Adam")
to<-c("Lary","Jack","Tom","Lary")
from_group<-c("A","A","A","C")
to_group<-c("B","A","D","B")
A<-data.frame(from,to,from_group,to_group)

  from   to from_group to_group
1 Jack Lary          A        B
2 Bill Jack          A        A
3 Jack  Tom          A        D
4 Adam Lary          C        B

我想将前两列合并为具有所有唯一名称的一列,将后两列合并为另一列,其中包含所有相关组,例如:

  names groups
1  Jack      A
2  Bill      A
3  Adam      C
4  Lary      B
5   Tom      D

标签: r

解决方案


你可以unique使用unlist

unique(data.frame(names=unlist(A[1:2]), groups=unlist(A[3:4])))
#      names groups
#from1  Jack      A
#from2  Bill      A
#from4  Adam      C
#to1    Lary      B
#to3     Tom      D

或没有行名:

unique(data.frame(names=unlist(A[1:2], use.names = FALSE),
                  groups=unlist(A[3:4], use.names = FALSE)))
#  names groups
#1  Jack      A
#2  Bill      A
#4  Adam      C
#5  Lary      B
#7   Tom      D

或使用名称

i <- endsWith(names(A), "_group")
unique(data.frame(names=unlist(A[!i]), groups=unlist(A[i])))

推荐阅读