R累计时差

我想从一开始就计算累计时间差。我编写了一个粗糙的解决方案,我并不特别喜欢。有人可以在dplyr管道中使用更优雅,更可靠的解决方案吗?期望结果应与diffCum列中相同。

require(dplyr)

d = data.frame(n = 1:3, t = lubridate::ymd_hms("2020-03-30 08:15:39","2020-03-30 10:15:39","2020-03-30 14:15:39")) %>%
  mutate(diffMin = difftime(t, lag(t,1), unit = "mins")) %>%
  mutate(diffMin = ifelse(is.na(diffMin), 0, diffMin)) %>% # error prone as it would capture other NAs 
  mutate(diffCum = cumsum(diffMin)) # does not work with difftime class
评论
  • d小调
    d小调 回复

    我不确定“捕获其他NA”是什么意思,也不确定是否符合条件!

    d <- 
      data.frame(n = 1:3, t = lubridate::ymd_hms("2020-03-30 08:15:39","2020-03-30 10:15:39","2020-03-30 14:15:39")) %>%
      mutate(
        diffMin = difftime(t, lag(t,1, default = 0 ), unit = "mins") %>% 
          as.numeric() %>%
          cumsum()
        )