r - 将行分组到对话并添加对话编号
问题描述
我有一个文件,其中包含客户和代理之间的消息,但这些消息没有按对话分组,即有唯一的对话 ID。幸运的是,原始消息包含在对该消息的后续回复中。该消息位于“文本”列中。这可以通过以下示例轻松解释
actionDateTime text response postTime
2019-01-01 12:00 Hi N/A 2019-01-01 12:00
2019-01-01 12:01 Hi Hello! 2019-01-01 12:00
2019-01-01 12:02 Hi How can I help? 2019-01-01 12:00
.
.
.
2019-01-02 12:00 Hi there N/A 2019-01-01 12:00
2019-01-02 12:01 Hi there Morning 2019-01-01 12:00
2019-01-02 12:02 Hi there How can I help? 2019-01-01 12:00
所以我尝试了下面的代码进行分组,但这不起作用。
df %>%
group_by(text, postTime) %>%
mutate(convID = row_number()) %>%
ungroup()
这确实输出了一个带有 convID 的文件,但不是我想要的方式。事实上,我不明白它是如何编号的。我相信那是因为我在 group_by 中使用了两个变量。然而,只使用一个是行不通的,因为两个不同的人可以同时发消息,或者两个不同的消息看起来很相似(例如,很多人可以只以“嗨”开头)。
当我只尝试组“文本”时,它仍然会在对话中给我数字,而不是唯一的 ID。再次说明如下
我得到了什么
text response postTime convID
Hi N/A 2019-01-01 12:00 1
Hi Hello! 2019-01-01 12:00 2
Hi How can I help? 2019-01-01 12:00 3
.
.
.
Hi there N/A 2019-01-01 12:00 1
Hi there Morning 2019-01-01 12:00 2
Hi there How can I help? 2019-01-01 12:00 3
我想要的是:
text response postTime convID
Hi N/A 2019-01-01 12:00 1
Hi Hello! 2019-01-01 12:00 1
Hi How can I help? 2019-01-01 12:00 1
.
.
.
Hi there N/A 2019-01-01 12:00 2
Hi there Morning 2019-01-01 12:00 2
Hi there How can I help? 2019-01-01 12:00 2
有什么帮助吗?
解决方案
我们可能需要group_indices
library(dplyr)
df %>%
mutate(convID = group_indices(., text, postTime))
# actionDateTime text response postTime convID
#1 2019-01-01 12:00 Hi N/A 2019-01-01 12:00 1
#2 2019-01-01 12:01 Hi Hello! 2019-01-01 12:00 1
#3 2019-01-01 12:02 Hi How can I help? 2019-01-01 12:00 1
#4 2019-01-02 12:00 Hi there N/A 2019-01-01 12:00 2
#5 2019-01-02 12:01 Hi there Morning 2019-01-01 12:00 2
#6 2019-01-02 12:02 Hi there How can I help? 2019-01-01 12:00 2
数据
df <- structure(list(actionDateTime = c("2019-01-01 12:00", "2019-01-01 12:01",
"2019-01-01 12:02", "2019-01-02 12:00", "2019-01-02 12:01", "2019-01-02 12:02"
), text = c("Hi", "Hi", "Hi", "Hi there", "Hi there", "Hi there"
), response = c("N/A", "Hello!", "How can I help?", "N/A", "Morning",
"How can I help?"), postTime = c("2019-01-01 12:00", "2019-01-01 12:00",
"2019-01-01 12:00", "2019-01-01 12:00", "2019-01-01 12:00", "2019-01-01 12:00"
)), class = "data.frame", row.names = c(NA, -6L))
推荐阅读
- java - 您如何将 2020-1-7(无尾随零)和 1/1/2020 格式的文本解析为 LocalDate?
- javascript - OPTIONS net::ERR_CONNECTION_REFUSED + 同源策略不允许读取远程资源(原因:CORS 请求未成功)
- python - 在 Python 中生成随机的 6 位 ID
- json - 单个空格/换行符/回车符/水平选项卡是否属于 json?
- c# - WCF 不活动超时
- node.js - 使用 Node.js 计算半径内的附近用户?
- javascript - 如何在数据表jquery中添加列过滤,除了操作列
- ruby-on-rails - 将数据从 RoR 中的其他两个表添加到中间表中
- java - 有没有办法在从 PostgreSQL 数据库表中获取的给定日期时间从 spring boot 自动调用函数?
- google-bigquery - 何时在 BigQuery 中使用分区