I have two columns, one is start_time and the other is end_time. The time is formmated in 24:00:00 time. I have situations when the start_time was at 23:00:00 and the end_time was at 02:00:00. How do I go about accounting for the duration from late nights to early mornings? Do I need to go down the route of case_when?
start_time | end_time | duration | start_date |
---|---|---|---|
16:34:23 | 19:24:45 | 2019-04-02 | |
23:12:34 | 04:12:34 | 2019-07-03 |
df_dur <- df %>%
mutate(duration = (end_time - start_time))
CodePudding user response:
I tidyverse option using the hms
could look as follows:
library(dplyr)
library(hms)
df %>%
mutate(across(1:2, ~ as_hms(.)),
duration = if_else(end_time < start_time,
as_hms(86400) - start_time end_time,
end_time - start_time))
# start_time end_time date duration
# 1 16:34:23 19:24:45 2019-04-02 10222 secs
# 2 23:12:34 04:12:34 2019-07-03 18000 secs
Data
df <- structure(list(start_time = c("16:34:23", "23:12:34"), end_time = c("19:24:45",
"04:12:34"), date = c("2019-04-02", "2019-07-03")), class = "data.frame", row.names = c(NA,
-2L))