首页 > 解决方案 > 将行分组到对话并添加对话编号

问题描述

我有一个文件,其中包含客户和代理之间的消息,但这些消息没有按对话分组,即有唯一的对话 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

有什么帮助吗?

标签: rdplyr

解决方案


我们可能需要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))

推荐阅读