Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Time taken between two activities

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading