I have a number of activities happening between two time points. I would like to get the time take n between start of next activity and end of the previous activity i.e. start2 - end1 ("2022-08-03 09:50:10" - "2022-08-03 09:30:50")
.
library(dplyr)
library(lubridate)
df <- tribble(
~activity, ~start, ~end,
"activity 1", ymd_hms("2022-08-03 08:32:50"), ymd_hms("2022-08-03 09:30:50"),
"activity 2", ymd_hms("2022-08-03 09:50:10"), ymd_hms("2022-08-03 10:11:12"),
"activity 3", ymd_hms("2022-08-03 10:30:12"), ymd_hms("2022-08-03 11:45:45"),
"activity 4", ymd_hms("2022-08-03 12:12:11"), ymd_hms("2022-08-03 12:50:11"),
"activity 5", ymd_hms("2022-08-03 13:10:50"), ymd_hms("2022-08-03 14:03:34"))
df
CodePudding user response:
Use -
with lag
:
library(dplyr)
df %>%
mutate(diff = start - lag(end))
activity start end diff
<chr> <dttm> <dttm> <drtn>
1 activity 1 2022-08-03 08:32:50 2022-08-03 09:30:50 NA mins
2 activity 2 2022-08-03 09:50:10 2022-08-03 10:11:12 19.33333 mins
3 activity 3 2022-08-03 10:30:12 2022-08-03 11:45:45 19.00000 mins
4 activity 4 2022-08-03 12:12:11 2022-08-03 12:50:11 26.43333 mins
5 activity 5 2022-08-03 13:10:50 2022-08-03 14:03:34 20.65000 mins