【问题标题】:combine or iterate dplyr rows on specific columns在特定列上组合或迭代 dplyr 行
【发布时间】:2017-09-22 09:46:21
【问题描述】:

我有一个数据集,其中包含两方之间的聊天对话。我想将数据集组合成第 1 个人和第 2 个人之间的逐行对话。

有时人们会输入多个句子,这些句子会在数据框中显示为多条记录。

这是我想弄清楚的伪代码。

  • 要合并的line_text
  • 时间戳以最新时间更新
  • 如果 line_by 显示同一个人输入了多行并且 通过他们的聊天发送
  • 因为在这个数据集中有多个 id 表示每个 人 1 和人 2 之间的对话记录,我想要 由每个唯一 ID 运行的循环。

这是数据框现在的样子:

id    timestamp line_by line_text
1234    02:54.3 Person1 Text Line 1
1234    03:23.8 Person2 Text Line 2
1234    03:47.0 Person2 Text Line 3
1234    04:46.8 Person1 Text Line 4
1234    05:46.2 Person1 Text Line 5
9876    06:44.5 Person2 Text Line 6
9876    07:27.6 Person1 Text Line 7
9876    08:17.5 Person2 Text Line 8
9876    10:20.3 Person2 Text Line 9

我想看看数据改成如下:

id    timestamp line_by line_text
1234    02:54.3 Person1 Text Line 1
1234    03:47.0 Person2 Text Line 2Text Line 3
1234    05:46.2 Person1 Text Line 4Text Line 5
9876    06:44.5 Person2 Text Line 6
9876    07:27.6 Person1 Text Line 7
9876    10:20.3 Person2 Text Line 8Text Line 9

披露:我问过同样的问题,但对于 python 中的熊猫。这就是我卡在 R 和 Python 的地方。

【问题讨论】:

  • 看起来在第二个数据帧(你想要的那个)中,id 1234 Person 2 的 Text Line 2 的时间戳不正确(应该是 03:23.8,但显示为 03 :47.0)。我不确定我是否理解您在这里寻找的模式......

标签: r dplyr data-science


【解决方案1】:

试试这个

library(dplyr)
library(data.table)
df %>%
  group_by(id, grp = rleid(line_by)) %>%
  summarise(timestamp = last(timestamp),
            line_by = unique(line_by), line_text = paste(line_text, collapse=", ")) %>%
  select(-grp)

诀窍是除了id 之外,还按rleid(...) 分组

输出

# A tibble: 6 x 4
# Groups:   id [2]
     # id timestamp line_by            line_text
  # <int>     <chr>   <chr>                <chr>
# 1  1234   02:54.3 Person1            TextLine1
# 2  1234   03:47.0 Person2 TextLine2, TextLine3
# 3  1234   05:46.2 Person1 TextLine4, TextLine5
# 4  9876   06:44.5 Person2            TextLine6
# 5  9876   07:27.6 Person1            TextLine7
# 6  9876   10:20.3 Person2 TextLine8, TextLine9

【讨论】:

  • 我真希望dplyr 有自己的rleid 版本,我开始尝试回答这个问题,但后来因为想知道如何写一个而分心!
  • 谢谢。这完美地完成了这项工作。
【解决方案2】:

仅使用 dplyr 的变体:

library(dplyr)
df %>% group_by(id,line_by,grp = cumsum(line_by !=lag(line_by,1,""))) %>%
  summarise(timestamp = last(timestamp),line_text = paste(line_text,collapse="")) %>%
  select(-grp)

【讨论】:

    猜你喜欢
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 2015-12-29
    • 2021-02-08
    • 2012-06-22
    • 1970-01-01
    相关资源
    最近更新 更多