R: Merge of rows in same data table, concatenating certain columns

感情迁移 提交于 2019-12-08 23:13:16

问题


I have my data table in R. I want to merge rows which have an identical customerID, and then concatenate the elements of other merged columns.

I want to go from this:

   title  author customerID
1 title1 author1          1
2 title2 author2          2
3 title3 author3          1

to this:

           title           author Group.1
1 title1, title3 author1, author3       1
2         title2          author2       2

回答1:


The aggregate function should help you in finding a solution:

dat = data.frame(title = c("title1", "title2", "title3"),
                 author = c("author1", "author2", "author3"),
                 customerID = c(1, 2, 1))
aggregate(dat[-3], by=list(dat$customerID), c)
#   Group.1 title author
# 1       1  1, 3   1, 3
# 2       2     2      2

Or, just make sure you add stringsAsFactors = FALSE when you are creating your data frame and you're pretty much good to go. If your data are already factored, you can use something like dat[c(1, 2)] = apply(dat[-3], 2, as.character) to convert them to character first, then:

aggregate(dat[-3], by=list(dat$customerID), c)
#   Group.1          title           author
# 1       1 title1, title3 author1, author3
# 2       2         title2          author2



回答2:


Maybe not the best solution but easy to understand:

df <- data.frame(author=LETTERS[1:5], title=LETTERS[1:5], id=c(1, 2, 1, 2, 3), stringsAsFactors=FALSE)

uniqueIds <- unique(df$id)

mergedDf <- df[1:length(uniqueIds),]

for (i in seq(along=uniqueIds)) {
    mergedDf[i, "id"] <- uniqueIds[i]
    mergedDf[i, "author"] <- paste(df[df$id == uniqueIds[i], "author"], collapse=",")
    mergedDf[i, "title"] <- paste(df[df$id == uniqueIds[i], "title"], collapse=",")
}

mergedDf
#  author title id
#1    A,C   A,C  1
#2    B,D   B,D  2
#3      E     E  3


来源:https://stackoverflow.com/questions/11364992/r-merge-of-rows-in-same-data-table-concatenating-certain-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!