The 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