difftime between rows using dplyr

后端 未结 2 555
醉梦人生
醉梦人生 2021-02-10 01:37

I\'m trying to calculate the time difference between two timestamps in two adjacent rows using the dplyr package. Here\'s the code:

    tidy_ex <- function ()         


        
相关标签:
2条回答
  • 2021-02-10 01:53

    Alternatively, you can simply try:

    ... %>%
    mutate(diff = c(0,diff(timestamp)))
    

    Or, if you want to explicitly assign the unit and convert the column to numeric for other calculations:

    ... %>%
    mutate(diff = c(0,as.numeric(diff(timestamp), units="mins")))
    
    0 讨论(0)
  • 2021-02-10 01:56

    Thanks to Victorp for the suggestion. I changed the mutate line to:

    mutate(diff = c(difftime(tail(timestamp, -1), head(timestamp, -1)),0))
    

    (The 0 I placed at the end so the difference calculation would start in the first row).

    0 讨论(0)
提交回复
热议问题