【发布时间】:2020-02-26 00:07:54
【问题描述】:
我在 R 中有一个数据框,我想在其中合并某些行并组合这些行中某些单元格的值。想象一下以下数据框:
Col.1<-c("a","b","b","a","c","c","c","d")
Col.2<-c("mouse", "cat", "dog", "bird", "giraffe", "elephant", "zebra", "worm")
df<-data.frame(Col.1, Col.2)
df
Col.1 Col.2
a mouse
b cat
b dog
a bird
c giraffe
c elephant
c zebra
d worm
我想合并 Col.1 中的值相同的所有相邻行,并相应地合并 Col.2 中的值。
最终的结果应该是这样的:
Col.1 Col.2
a mouse
b cat dog
a bird
c giraffe elephant zebra
d worm
我尝试使用 dplyr 解决方案(例如:ddply(df, .(Col.1), summarize, Col.2 = sum(Col.2))),但 sum-command 不适用于因子值。
【问题讨论】: