0

I need to calculate the elapsed time between start and stop, I have example data below

eg_data <- data.frame(
ID = c(1,1,1,1,1,1,1,1,1,1) , 
date = c('20181101','20181101','20181101','20181101','20181101','20181101','20181101','20181101','20181101','20181101') , 
start = c("12:05","13:55","15:00","16:40","18:15", "18:50", "19:40", "20:20", "21:00", "22:15") ,
stop =  c("13:10","14:40","15:30","17:30","18:45", "19:20", "20:05", "20:50", "21:30", "22:55"))

For each ID (there is only one here for example), I need to calculate the time elapsed between the stop of row X, and the start of row X+1. EG for row 1, and answer would be NA b/c I have no stop time to compare. For row 2, the difference between stop time in row1 (13:10), and start time in row2 (13:55) is 45 minutes.

There is another example dataset below that has a final column that is what I need, I am just unsure how to calculate it in R.

Look at start time in rowX, stop time in rowX-1, calculate difference, and put it in column in rowX.

eg_data2 <- data.frame(
ID = c(1,1,1,1,1,1,1,1,1,1) , 
date = c('20181101','20181101','20181101','20181101','20181101','20181101','20181101','20181101','20181101','20181101') , 
start = c("12:05","13:55","15:00","16:40","18:15", "18:50", "19:40", "20:20", "21:00", "22:15") ,
stop =  c("13:10","14:40","15:30","17:30","18:45", "19:20", "20:05", "20:50", "21:30", "22:55") ,
diff_stp1_sta2 = c(NA,45,20,70,45,5,20,15,10,45))
Adam_S
  • 687
  • 2
  • 12
  • 24
  • 1
    I think this should get you going: [Calculate difference between values in consecutive rows by group](https://stackoverflow.com/questions/14846547/calculate-difference-between-values-in-consecutive-rows-by-group?lq=1) – Henrik Nov 19 '18 at 20:15
  • First convert your strings to appropriate time or date/time classes. Use `chron::times` if the dates don't matter, use `POSIXct` to incorporate the data as well. Then it's simple with `dplyr`: `group_by(eg_data, ID, diff = start - lag(stop))`. – Gregor Thomas Nov 19 '18 at 20:16
  • A quick look at Henrik's solution, I think the answer I need is in there, and it also has the lag aspect of dplyr that Gregor mentioned. Thank you! – Adam_S Nov 19 '18 at 20:27

0 Answers0