11

我在 R 中有我的数据表。我想合并具有相同 的行customerID,然后连接其他合并列的元素。

我想从这个出发:

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

对此:

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

2 回答 2

14

aggregate功能应该可以帮助您找到解决方案:

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

或者,只要确保stringsAsFactors = FALSE在创建数据框时添加,就可以了。如果您的数据已经被考虑在内,您可以使用类似dat[c(1, 2)] = apply(dat[-3], 2, as.character)先将它们转换为字符的方法,然后:

aggregate(dat[-3], by=list(dat$customerID), c)
#   Group.1          title           author
# 1       1 title1, title3 author1, author3
# 2       2         title2          author2
于 2012-07-06T17:06:21.783 回答
3

也许不是最好的解决方案,但很容易理解:

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
于 2012-07-06T16:56:42.100 回答