Calculating the difference between consecutive rows by group using dplyr?

前端 未结 2 984
悲哀的现实
悲哀的现实 2020-12-14 09:53

I have a dataframe of ids and timestamps. I\'d like to calculate the difference between each sequential timestamp for an individual id.

My dataframe looks like this:

相关标签:
2条回答
  • 2020-12-14 10:04

    using data.table

    library(data.table)
    library(dplyr)
    setDT(dat)[, time.difference := time - lag(time, 1L), by = id]
    
    0 讨论(0)
  • 2020-12-14 10:20

    Like this:

    dat %>% 
      group_by(id) %>% 
      mutate(time.difference = time - lag(time))
    
    0 讨论(0)
提交回复
热议问题