我是R的初学者。我在R中有数据框如下:
Id Values
A_0_d Low_5524; Low_6412; Hi_50567
A_0_d Low_5509; Low_6412; Low_6897; Hi_16021
A_0_d Low_5524; Low_4930; Low_5886
B_1_d Low_3697; Low_4519; Low_5524
C_3_d Low_5576; Low_5581
C_3_d Hi_30246
C_3_d Low_5576; Hi_30246
我想基于Ids聚合数据帧,即在一行中将相同ID的所有值分组,并保留仅如下的唯一条目:
A_0_d Low_5524; Low_6412; Hi_50567; Low_5509; Low_6897; Hi_16021; Low_4930; Low_5886
B_1_d Low_3697; Low_4519; Low_5524
C_3_d Low_5576; Low_5581; Hi_30246
我可以使用聚合功能。请指导我。
答案 0 :(得分:3)
使用aggregate
你可以试试这个
aggregate(Values ~ Id, df, function(x) paste(unique(x), collapse = '; '))
答案 1 :(得分:2)
转换' data.frame'到' data.table' (setDT(df1)
)。然后,split
'值'按"; "
分组后,输入“{1}”,unlist
输出,获取unique
元素和paste
library(data.table)
setDT(df1)[, .(Values = paste(unique(unlist(strsplit(Values, "; "))),
collapse="; ")), by = Id]
# Id
#1: A_0_d
#2: B_1_d
#3: C_3_d
# Values
#1: Low_5524; Low_6412; Hi_50567; Low_5509; Low_6897; Hi_16021; Low_4930; Low_5886
#2: Low_3697; Low_4519; Low_5524
#3: Low_5576; Low_5581; Hi_30246
答案 2 :(得分:2)
使用aggregate
即可
aggregate(Values~Id, df, function(x) unique(unlist(strsplit(x, ";"))))
# Id Values
#1 A_0_d Low_5524, Low_6412, Hi_50567, Low_5509, Low_6897, Hi_16021, Low_4930, Low_5886
#2 B_1_d Low_3697, Low_4519, Low_5524
#3 C_3_d Low_5576, Low_5581, Hi_30246