I have a time variable as hh:mm. I want to add numeric minutes to that. If time goes over 24:00, it should count a new day.
For example: time starts at 23:45, delay is 20 minutes, real start time is 00:05. Example data frame:
df <- data.frame(time_start = c("23:45", "23:30", NA, "23:00", "00:30", "02:00"),
delay = c(20, 300, 10, 120, 5, 0)) # in minutes
This is my way to get minutes to a time format:
library(chron)
library(lubridate)
df$delay<- hms(times(df$delay/24))
But adding delay to time_start results in times > 24 hours. How can I start from a new day? Thanks in advance!
You could add a "neutral" date (e.g. "1970-01-01"
) to your time and format as.POSIXct
. Then just add the delay (in seconds, therefore * 60
). To finally display just the time, use format
.
df <- transform(df, time_start2=as.POSIXct(
ifelse(is.na(time_start), NA, paste(as.Date("1970-01-01"), time_start))
))
df$time_end <- format(with(df, time_start2 + delay * 60), "%H:%M")
df
# time_start delay time_start2 time_end
# 1 23:45 20 1970-01-01 23:45:00 00:05
# 2 23:30 300 1970-01-01 23:30:00 04:30
# 3 <NA> 10 <NA> <NA>
# 4 23:00 120 1970-01-01 23:00:00 01:00
# 5 00:30 5 1970-01-01 00:30:00 00:35
# 6 02:00 0 1970-01-01 02:00:00 02:00