MaxMiak
MaxMiak

Reputation: 197

Timestamps difference

I have a data frame which contains two timestamps as in start and end as below I cant find the difference of these two but what I want is the difference between start of second row and end of first row. My data is

time_df <- data.frame(start=as.POSIXct(c('2020-08-23 07:40:59','2020-08-23 08:22:28','2020-08-23 08:54:46','2020-08-23 09:23:17','2020-08-24 07:39:10','2020-08-24 08:13:06','2020-09-01 10:21:04','2020-09-02 06:14:54','2020-09-02 07:44:59'))
,end=as.POSIXct(c('2020-08-23 08:15:23','2020-08-23 08:46:41','2020-08-23 09:17:05','2020-08-23 09:51:20','2020-08-24 08:09:29','2020-08-24 08:37:45','2020-09-01 10:56:41','2020-09-02 06:43:02','2020-09-02 08:08:50')))

What I am trying

time_df$duration <- as.numeric(difftime(time_df$end,time_df$start,units ="mins"))

but I want to find the difference between start of second row and end of first row keeping above data frame in min I want the difference of (8:22:28 - 8:15:23)

Upvotes: 2

Views: 34

Answers (2)

jay.sf
jay.sf

Reputation: 73802

Using rowSums. Convert end as.numeric to get the negative sign.

d <- rowSums(cbind(-as.numeric(time_df$end[-nrow(time_df)]), time_df$start[-1]))

d  ## seconds
# [1]    425    485    372  78470    217 697399  69493   3717

d/60  ## minutes
# [1]     7.083333     8.083333     6.200000  1307.833333
# [5]     3.616667 11623.316667  1158.216667    61.950000

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

You can remove the 1st value from start and last value from end so that you can get difference of 2nd value of start and 1st value of end, 3rd value of start and 2nd value of end and so on. We append a NA value at the beginning to make the length equal to number of rows.

time_df$diff <- c(NA, difftime(time_df$start[-1], 
                               time_df$end[-nrow(time_df)], units = 'mins'))

Or if you use dplyr, you can use lag to get previous value :

library(dplyr)
time_df %>% mutate(diff = difftime(start, lag(end), units = 'mins'))

#                start                 end         diff
#1 2020-08-23 07:40:59 2020-08-23 08:15:23      NA mins
#2 2020-08-23 08:22:28 2020-08-23 08:46:41     7.1 mins
#3 2020-08-23 08:54:46 2020-08-23 09:17:05     8.1 mins
#4 2020-08-23 09:23:17 2020-08-23 09:51:20     6.2 mins
#5 2020-08-24 07:39:10 2020-08-24 08:09:29  1307.8 mins
#6 2020-08-24 08:13:06 2020-08-24 08:37:45     3.6 mins
#7 2020-09-01 10:21:04 2020-09-01 10:56:41 11623.3 mins
#8 2020-09-02 06:14:54 2020-09-02 06:43:02  1158.2 mins
#9 2020-09-02 07:44:59 2020-09-02 08:08:50    62.0 mins

Upvotes: 1

Related Questions