How to calculate time difference with previous row of a data.frame by group

前端 未结 2 2049
心在旅途
心在旅途 2020-12-01 12:46

The problem I am trying to solve is that I have a data frame with a sorted POSIXct variable in it. Each row is categorized and I want to get the time differences between eac

2条回答
  •  既然无缘
    2020-12-01 13:10

    Try this:

    library(dplyr)
    df %>%
      arrange(category, randtime) %>%
      group_by(category) %>%
      mutate(diff = randtime - lag(randtime),
             diff_secs = as.numeric(diff, units = 'secs'))
    
    #   category            randtime             diff   diff_secs
    #     (fctr)              (time)           (dfft)       (dbl)
    # 1        A 2015-06-01 11:10:54         NA hours          NA
    # 2        A 2015-06-01 15:35:04   4.402785 hours   15850.027
    # 3        A 2015-06-01 17:01:22   1.438395 hours    5178.222
    # 4        B 2015-06-01 08:14:46         NA hours          NA
    # 5        B 2015-06-01 16:53:43 518.955379 hours 1868239.364
    # 6        B 2015-06-01 17:37:48  44.090950 hours  158727.420
    

    You may also want to add replace(is.na(.), 0) to the chain.

提交回复
热议问题