Letter Group
A 1
B 1
C 1
D 2
E 2
成为:
Letter Group SameGroup
A 1 B,C
B 1 A,C
C 1 A,B
D 2 E
E 2 D
答案 0 :(得分:3)
您可以尝试:
df$SameGroup<-mapply(function(x,y)
toString(setdiff(x,y)),
ave(df$Letter,df$Group,FUN= list),df$Letter)
# Letter Group SameGroup
#1 A 1 B, C
#2 B 1 A, C
#3 C 1 A, B
#4 D 2 E
#5 E 2 D
数据强>
df<-structure(list(Letter = c("A", "B", "C", "D", "E"), Group = c(1,
1, 1, 2, 2)), .Names = c("Letter", "Group"), row.names = c(NA,
-5L), class = "data.frame")
答案 1 :(得分:0)
以下是使用data.table
的选项。我们将'data.frame'转换为'data.table'(setDT(df)
),按'Group'分组,循环遍历行序列,根据序列子集'Letter',转换为{{1并将(list
)指定为“SameGroup”
:=