在合并(粘贴)r中选定行的数据时,如何防止最终数据中重复元素
我想在R中组合一个data.frame的多行 这是我的data.frame:在合并(粘贴)r中选定行的数据时,如何防止最终数据中重复元素,r,R,我想在R中组合一个data.frame的多行 这是我的data.frame: df<-data.frame(col1 = c("color","color","color","day","day","year"), col2=c("red","red","red",1,1,18), col3=c("red","blue","blue",10,12,17), col4=c("red"
df<-data.frame(col1 = c("color","color","color","day","day","year"),
col2=c("red","red","red",1,1,18),
col3=c("red","blue","blue",10,12,17),
col4=c("red","blue","green",13,13,12))
df
col1 col2 col3 col4
1 color red red red
2 color red blue blue
3 color red blue green
4 day 1 10 13
5 day 1 12 13
6 year 18 17 12
结果是:
Group.1 col1 col2 col3
1 color color, color, color red, red, red red, blue, blue
2 day day, day 1, 1 10, 12
3 year year 18 17
col4
1 red, blue, green
2 13, 13
3 12
但是,如何合并同名行的元素以生成如下data.frame:
col1 col2 col3 col4
1 color red red//blue red//blue//green
2 day 1 10//12 13
3 year 18 17 12
非常感谢。数据:
df <- data.frame(
col1 = c("color","color","color","day","day","year"),
col2 = c("red","red","red",1,1,18),
col3 = c("red","blue","blue",10,12,17),
col4 = c("red","blue","green",13,13,12),
stringsAsFactors = FALSE)
说明:
aggregate()
unique()
中包装x
,以避免出现“1//1”之类的情况图像对任何人都没有帮助。请看一看,以了解提供示例数据的方法
df <- data.frame(
col1 = c("color","color","color","day","day","year"),
col2 = c("red","red","red",1,1,18),
col3 = c("red","blue","blue",10,12,17),
col4 = c("red","blue","green",13,13,12),
stringsAsFactors = FALSE)
aggregate(df[,-1], by=df["col1"], function(x) paste(unique(x), collapse="//"))