3

我有一个看起来像这样的数据框:

_________________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"

有没有办法做到这一点?我正在从数据库表中导入,并且我有很多数据,所以我不能手动进行。

4

1 回答 1

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
于 2013-01-28T16:43:56.433 回答