我有一个如下所示的数据框:
_________________id ________________text______
1 | 7821 | "some text here"
2 | 7821 | "here as well"
3 | 7821 | "and here"
4 | 567 | "etcetera"
5 | 567 | "more text"
6 | 231 | "other text"
我想按ID对文本进行分组,因此我可以运行聚类算法:
________________id___________________text______
1 | 7821 | "some text here here as well and here"
2 | 567 | "etcetera more text"
3 | 231 | "other text"
有没有办法做到这一点?我从数据库表导入,我有很多数据,所以我不能手动完成。
答案 0 :(得分:10)
您实际上是在寻找aggregate
,而不是merge
,并且应该在SO上显示许多示例,以展示不同的聚合选项。这是最基本和最直接的方法,使用公式方法指定aggregate
的哪些列。
以下是您可以复制并粘贴的数据
mydata <- structure(list(id = c(7821L, 7821L, 7821L, 567L, 567L, 231L),
text = structure(c(6L, 3L, 1L, 2L, 4L, 5L), .Label = c("and here",
"etcetera", "here as well", "more text", "other text", "some text here"
), class = "factor")), .Names = c("id", "text"), class = "data.frame",
row.names = c(NA, -6L))
这是汇总输出。
aggregate(text ~ id, mydata, paste, collapse = " ")
# id text
# 1 231 other text
# 2 567 etcetera more text
# 3 7821 some text here here as well and here
当然,还有data.table
,它具有非常紧凑的语法(并且速度极快):
> library(data.table)
> DT <- data.table(mydata)
> DT[, paste(text, collapse = " "), by = "id"]
id V1
1: 7821 some text here here as well and here
2: 567 etcetera more text
3: 231 other text