FiofanS FiofanS - 1 month ago 8
R Question

Time difference between two time stamps

I have a dataframe that contains the following datetime stamps of the class

"POSIXct" "POSIXt"
:

1899-12-30 08:00:37
1899-12-30 08:03:54
1899-12-30 08:05:31
1899-12-30 08:12:55


I need to calculate the difference (in minutes) between subsequent rows. The result for the first row should be (i.e. 08:03:54-08:00:37):

1899-12-30 08:00:37 3.28


I use this code to calculate the difference, but the outputs do not coincide with manual calculations.

c_time <- df$datetime
intervals = c(difftime(ymd_hms(c_time[2:length(c_time)]),
ymd_hms(c_time[1:(length(c_time)-1)]),
units="mins"),0)

Answer

You could use lubridate and dplyr. It is one option among others.

df <- data.frame(dtime = c(
"1899-12-30 08:00:37",
"1899-12-30 08:03:54",
"1899-12-30 08:05:31",
"1899-12-30 08:12:55"))

library(dplyr)
library(lubridate)
df %>%
  mutate(dtime = ymd_hms(dtime), 
         diff = lead(dtime) - dtime)
#>                 dtime          diff
#> 1 1899-12-30 08:00:37 3.283333 mins
#> 2 1899-12-30 08:03:54 1.616667 mins
#> 3 1899-12-30 08:05:31 7.400000 mins
#> 4 1899-12-30 08:12:55       NA mins