合并R中的行与连接列中内容的相同行名称

时间:2015-06-24 08:46:20

标签: r

我需要帮助通过连接其中一列中的内容来合并具有相同名称的行。例如,在我的数据框df中,除了col 3之外,具有相同名称的行完全匹配列。我想合并具有相同rowname的行并连接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

1 个答案:

答案 0 :(得分:2)

尝试

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")
相关问题