I have a dataframe of stage starting times and stage ending times. I want to subtract the starting time of one stage from the ending time of the previous stage. I.e., I want to subtract the nth cell from one column and from the n-1 cell in a different column. This is easy to do in Excel, but I am not sure how to do it in R.
Here is what the data looks like. I included the dput() of the data as well:
#test data frame
Stage StartTime EndTime
102 2021-07-19 17:23:00 2021-07-19 21:53:24
103 2021-07-19 21:54:00 2021-07-19 23:00:14
104 2021-07-19 23:01:00 2021-07-20 00:50:10
105 2021-07-20 00:51:00 2021-07-20 01:50:58
106 2021-07-20 01:51:00 2021-07-20 03:28:22
107 2021-07-20 03:29:00 2021-07-20 04:28:00
108 2021-07-20 05:38:00 2021-07-20 08:19:26
> dput(test[1:7,])
structure(list(Stage = c(102, 103, 104, 105, 106, 107, 108),
StartTime = structure(c(1626733380, 1626749640, 1626753660,
1626760260, 1626763860, 1626769740, 1626777480), tzone = "", class = c("POSIXct",
"POSIXt")), EndTime = structure(c(1626749604, 1626753614,
1626760210, 1626763858, 1626769702, 1626773280, 1626787166
), tzone = "", class = c("POSIXct", "POSIXt")), row.names = c(NA, -7L), class = c("tbl_df",
"tbl", "data.frame"))
For example, I know that I can do the following manually to get the time difference between the end of stage 102 and the start of stage 103 by doing:
as.numeric(difftime("2021-07-19 21:54:00", "2021-07-19 21:53:24", units='sec'))
> 36
I tried to make it more general, but this does NOT work. However, the idea would be to add 1 to the row index every time:
#does not work
# want to subtract row 2, col 2 - the later starting time
# from row 1, col 3 - the earlier end time
as.numeric(difftime(test[1,3], test[2,2], units='sec'))
It doesn't matter where the time difference is saved, whether a new column inside the dataframe or a completely new dataframe. Whatever works. I am really not sure how to do this. Maybe a loop? Any help would be appreciated. Thank you.