【问题标题】:Computing the sum of datetime intervals between rows within individuals (R)计算个人内行之间的日期时间间隔的总和 (R)
【发布时间】:2021-08-06 23:16:41
【问题描述】:

我想改变一个按ID 分组的新列,并总结每个会话之间的间隔。间隔定义为End 时间与其后续Start 时间之间的差异。例如,对于 ID 1,这将是 (2021-07-11 05:55:00 - 2021-07-11 01:14:00 = 281mins) 和 (2021-07-11 11:08:00 - 2021-07-11 08:09:00 = 179mins) 的总和,即 460。

df <- structure(list(ID = c(1, 1, 1, 2, 2, 2), Start = structure(c(1625931780, 
1625954100, 1625972880, 1625505720, 1625517480, 1625526900), class = c("POSIXct", 
"POSIXt"), tzone = "Singapore"), End = structure(c(1625937240, 
1625962140, 1625981580, 1625513640, 1625523300, 1625531880), class = c("POSIXct", 
"POSIXt"), tzone = "Singapore"), n = c(3L, 3L, 3L, 3L, 3L, 3L
)), row.names = c(NA, 6L), class = "data.frame")

  ID               Start                 End n
1  1 2021-07-10 23:43:00 2021-07-11 01:14:00 3
2  1 2021-07-11 05:55:00 2021-07-11 08:09:00 3
3  1 2021-07-11 11:08:00 2021-07-11 13:33:00 3
4  2 2021-07-06 01:22:00 2021-07-06 03:34:00 3
5  2 2021-07-06 04:38:00 2021-07-06 06:15:00 3
6  2 2021-07-06 07:15:00 2021-07-06 08:38:00 3

期望:

  ID               Start                 End n sumIntervals
1  1 2021-07-10 23:43:00 2021-07-11 01:14:00 3          460
2  1 2021-07-11 05:55:00 2021-07-11 08:09:00 3          460
3  1 2021-07-11 11:08:00 2021-07-11 13:33:00 3          460
4  2 2021-07-06 01:22:00 2021-07-06 03:34:00 3          124
5  2 2021-07-06 04:38:00 2021-07-06 06:15:00 3          124
6  2 2021-07-06 07:15:00 2021-07-06 08:38:00 3          124

注意: Start 和 End 在POSIXct 中,每个ID 中的会话数不是恒定的,所以可以是任意数量的@987654332 @。此处使用n=3进行说明。

任何帮助将不胜感激!

【问题讨论】:

  • n 在我们进行分组后就不需要了

标签: r datetime posixct


【解决方案1】:

我们可以在按“ID”分组后取“开始”的lead,使用difftime从“结束”和sum得到“分钟”的差异integer转换值

library(dplyr)
df <- df %>%
      group_by(ID) %>%
      mutate(new = sum(as.integer(difftime(lead(Start), End, 
             units = 'mins')), na.rm = TRUE) ) %>%
      ungroup

-输出

# A tibble: 6 x 5
     ID Start               End                     n   new
  <dbl> <dttm>              <dttm>              <int> <int>
1     1 2021-07-10 23:43:00 2021-07-11 01:14:00     3   460
2     1 2021-07-11 05:55:00 2021-07-11 08:09:00     3   460
3     1 2021-07-11 11:08:00 2021-07-11 13:33:00     3   460
4     2 2021-07-06 01:22:00 2021-07-06 03:34:00     3   124
5     2 2021-07-06 04:38:00 2021-07-06 06:15:00     3   124
6     2 2021-07-06 07:15:00 2021-07-06 08:38:00     3   124

【讨论】:

  • 非常感谢。你能解释一下铅的作用吗?阅读文档并不确定它在做什么。
  • @TYL 假设您有v1 &lt;- 1:5; lead(v1)#[1] 2 3 4 5 NA# shift by default n = 1`,因此下一行将移动到当前元素。请注意,最后一个元素默认填充为 NA。因此,当我们执行difftime 时,我们会为组中的最后一行得到NA,在sum 中用na.rm = TRUE 将其删除
  • 感谢您的解释!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 2012-03-26
  • 1970-01-01
相关资源
最近更新 更多