Search code examples
rdifftime

difftime within same column


The data frame is like this:

db = (name = c('A','A','A', 'B','B','B','B', 'C','C'),
      time = c('09/09/15 0:37:45', '09/09/15 0:39:45', '09/09/15 1:39:15', '09/10/15'20:35:20, '09/10/15 20:45:40', '09/10/15 20:47:00', '09/10/15 21:47:00' ,'09/11/15 7:15:15', '09/11/15 17:15:30')

What I want to get is the minutes gap of time among each name, the data I want to get is like this:

db = (name = c('A','A','A', 'B','B','B','B', 'C','C'),
      gap = c(NA, 2, 59.5, NA, 10.33, 1.67, 60, NA, 600.25)

Can anyone solve this puzzle? Thank you!


Solution

  • library(dplyr)
    db %>% group_by(name) %>% mutate(gap=round(c(NA,diff(time)), 1))
    Source: local data frame [9 x 3]
    Groups: name [3]
    
        name                time   gap
      (fctr)              (time) (dbl)
    1      A 2015-09-09 00:37:45    NA
    2      A 2015-09-09 00:39:45   2.0
    3      A 2015-09-09 01:39:15  59.5
    4      B 2015-09-10 20:35:20    NA
    5      B 2015-09-10 20:45:40  10.3
    6      B 2015-09-10 20:47:00   1.3
    7      B 2015-09-10 21:47:00  60.0
    8      C 2015-09-11 07:15:15    NA
    9      C 2015-09-11 17:15:30  10.0