我想在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","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
我使用以下代码合并基于df $ col1的相同行:
aggregate(df, by=list(df$col1),paste)
结果是:
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(df[,-1], by=df["col1"], function(x) paste(unique(x), collapse="//"))
说明:
collapse
参数topaste()
在aggregate()
每个单元格中返回一个字符串,并且x
在unique()
以类似“1 // 1”避事本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句