r - 如何对数据集中列的元素进行排序和合并
问题描述
我需要对包含两列的数据表的消息进行情感分析:第一列是“用户”列表,第二列是“评论”列表。由于每个用户可能关联不同的消息,我需要对我的数据表进行子集化,以获得一个新的数据表,其中包含唯一用户 ID 以及在同一单元格中引用每个单个用户的所有消息的组合,使用数据.table 库。
要使用的代码是什么?
谢谢你。
解决方案
基于此样本数据:
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
如果您想用空格" "
或其他符号分隔注释,您可以更改值。
推荐阅读
- javascript - Javascript 对象:如何使键的值成为另一个键(不是键的值)?
- kubernetes - IBM Cloud Private 3.1 (Kubernetes) 上的 GlusterFS PVC 安装错误
- flutter - 如何在文本小部件上添加一个像线条一样的主题中断?
- python - 计算测量点和目标线之间的距离
- ubuntu - Jenkins:Ubuntu 16.04:Headless Chrome 无法启动:异常退出
- python - 将 2 个图像转换为 numpy 数组并逐像素比较
- javascript - 如何更改jQuery对象中对象类型的无序列表的ID
- java - 递归回溯仅适用于小输入。较大的输入会导致 stackOverFlow
- python - 获取不等于计数函数参数的变量的最佳方法?
- image - 如何通过放大、反应原生应用程序将 base64 图像上传到 S3