我需要帮助合并具有相同名称的行,通过连接其中一列中的内容。例如,在我的数据帧df中,具有相同名称的行在列中完全匹配,但在第3列中除外。我希望合并具有相同行名的行,并使用逗号将col3中的内容连接起来,得到如下所示的结果。谢谢你的帮助。
df
rowname col1 col2 col3
pat 122 A T
bus 222 G C
pat 122 A G
result
rowname col1 col2 col3
pat 122 A T,G
bus 222 G C发布于 2015-06-24 17:04:42
试一试
aggregate(col3~., df, FUN=toString)
# rowname col1 col2 col3
#1 pat 122 A T, G
#2 bus 222 G C或者使用dplyr
library(dplyr)
df %>%
group_by_(.dots=names(df)[1:3]) %>%
summarise(col3=toString(col3))
# rowname col1 col2 col3
#1 bus 222 G C
#2 pat 122 A T, G数据
df <- structure(list(rowname = c("pat", "bus", "pat"), col1 = c(122,
222, 122), col2 = c("A", "G", "A"), col3 = c("T", "C", "G")),
.Names = c("rowname",
"col1", "col2", "col3"), row.names = c(NA, -3L), class = "data.frame")https://stackoverflow.com/questions/31021868
复制相似问题