【问题标题】:How to sort and merge elements of a column in a dataset如何对数据集中列的元素进行排序和合并
【发布时间】:2021-02-27 04:22:14
【问题描述】:

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

要使用什么代码?

谢谢。

【问题讨论】:

  • 您的问题不清楚。例如,您所说的“组合”是什么意思?尝试提供一个示例,包括您的源表和所需的输出
  • 请以您的部分数据为例,以便人们更好地了解您要做什么
  • 请使用dput 或我们可以复制和使用的东西添加数据。还显示共享数据的预期输出。了解how to ask a good questionhow to give a reproducible example

标签: r merge datatable subset sentiment-analysis


【解决方案1】:

基于此样本数据:

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

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

【讨论】:

    猜你喜欢
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    相关资源
    最近更新 更多