使用dplyr

时间:2018-12-04 18:51:01

标签: r dplyr message lag

我有一些数据包含对话中的消息。我需要计算某人发回邮件的响应时间。我为两个参与者都有唯一的用户ID,但是,当我使用下面的代码时,它仅计算对话中每条消息的差异。我需要一种方法来计算响应和初始消息之间的总差。 (即,如果某人发送了多个初始消息而没有响应,则我需要从第一条消息到第一条响应之间的时间。)

    convonlinetest <- convonline %>%
      arrange(conversation_id, created_at) %>%
      group_by(conversation_id) %>%
        filter(n() > 1) %>%
      mutate(timediff = created_at - lag(created_at))

第一个问题要解决,非常感谢您的提前帮助!

编辑:一些示例数据

    structure(list(conversation_id = c(20000004844375, 20000004844378, 
    20000004913095, 20000004837800, 20000004808210, 20000004808210, 
    20000004837799, 20000004844377, 20000004808210, 20000004846076
    ), user_id = c(-33135869739921264, -33135869739921264, 
    57394627930234816, 
    -33135869739921264, -33135869739921264, -70893327136775872, 
    -33135869739921264, 
    -33135869739921264, -33135869739921264, -33135869739921264), 
    created_at = c("2016-05-31 16:46:27.614", "2016-05-31 16:46:28.387", 
    "2016-07-11 20:20:06.589", "2016-05-27 16:31:05.716", "2016-05-13 
    12:48:25.125", 
    "2016-05-10 18:58:30.396", "2016-05-27 16:31:05.451", "2016-05-31 
    16:46:27.981", 
    "2016-05-19 18:43:02.859", "2016-06-01 13:16:26.753"), course_name = 
    c("acct-2020-30i", 
    "acct-2020-30i", "acct-2020-30i", "acct-2020-30i", "acct-2020-30i", 
    "acct-2020-30i", "acct-2020-30i", "acct-2020-30i", "acct-2020-30i", 
    "acct-2020-30i")), row.names = c(NA, 10L), class = "data.frame")

编辑:找到解决方案

我很sm愧自己不记得聚合函数,但是效果很好。以为我将来会和任何人分享。

new <- aggregate(convonline, by=list(convonline$conversation_id,
    convonline$user_id, FUN=min)

final <- new %>%
  mutate(created_at = as.Date(created_at)) %>%
  arrange(conversation_id, created_at) %>%
  group_by(conversation_id) %>%
  mutate(diff = created_at - lag(created_at))

1 个答案:

答案 0 :(得分:0)

当我在一行中运行您的代码时,将created_at列从字符列更改为日期时间列,我得到的是预期的结果。

library(lubridate)  # great package for handling dates

data %>%
  mutate(created_at = as_datetime(created_at)) %>% # NEW ROW OF CODE 
  arrange(conversation_id, created_at) %>%
  group_by(conversation_id) %>%
  filter(n() > 1) %>%
  mutate(timediff = created_at - lag(created_at))

# A tibble: 3 x 5
# Groups:   conversation_id [1]
  conversation_id  user_id created_at          course_name   timediff       
            <dbl>    <dbl> <dttm>              <chr>         <time>         
1  20000004808210 -7.09e16 2016-05-10 18:58:30 acct-2020-30i "      NA days"
2  20000004808210 -3.31e16 2016-05-13 12:48:25 acct-2020-30i 2.742995 days  
3  20000004808210 -3.31e16 2016-05-19 18:43:02 acct-2020-30i 6.246270 days