首页 > 解决方案 > 如何对数据集中列的元素进行排序和合并

问题描述

我需要对包含两列的数据表的消息进行情感分析:第一列是“用户”列表,第二列是“评论”列表。由于每个用户可能关联不同的消息,我需要对我的数据表进行子集化,以获得一个新的数据表,其中包含唯一用户 ID 以及在同一单元格中引用每个单个用户的所有消息的组合,使用数据.table 库。

要使用的代码是什么?

谢谢你。

标签: rmergedatatablesubsetsentiment-analysis

解决方案


基于此样本数据:

DT <- structure(list(User.ID = c(111, 222, 333, 444, 555, 111, 111, 
222, 222), Comment = c("Comment 111", "Comment 222", "Comment 333", 
"Comment 444", "Comment 555", "Second Comment 111", "Third Comment 111", 
"Second Comment 222", "Third Comment 222")), class = "data.frame", row.names = c(NA, 
-9L))

看起来像这样:

   User.ID            Comment
1:     111        Comment 111
2:     222        Comment 222
3:     333        Comment 333
4:     444        Comment 444
5:     555        Comment 555
6:     111 Second Comment 111
7:     111  Third Comment 111
8:     222 Second Comment 222
9:     222  Third Comment 222

我们可以使用data.table

library(data.table)
setDT(DT)
DT[ , (id = paste(Comment, collapse=",")), by = User.ID][, .("User ID" = User.ID, Comment = V1)]

要得到:

 User ID                                          Comment
1:     111 Comment 111,Second Comment 111,Third Comment 111
2:     222 Comment 222,Second Comment 222,Third Comment 222
3:     333                                      Comment 333
4:     444                                      Comment 444
5:     555                                      Comment 555

collapse如果您想用空格" "或其他符号分隔注释,您可以更改值。


推荐阅读