简体   繁体   中英

Find mid time between two times in R, sometimes overnight

I would like to find the mid time between time 1 and time 2 in R. I already have the duration in hours. Sometimes it's overnight (row 1) and sometimes not (row 2).

Here are the first two rows in the data frame

dat <- data.frame(id=1:2, tm1=c("23:00","01:00"), tm2=c("07:00","06:00"), dur=c("8.0","5.0"))

数据框图片

So in row 1 the mid time should be 3:00 and in row 2 it should be 03:30.

you can just add half of the duration

format(strptime(dat$tm1,format = '%H:%M') + dat$dur*3600/2, format = '%H:%M')

Here is one way -

library(dplyr)

dat %>%
  mutate(across(starts_with('tm'), as.POSIXct, tz = 'UTC', format = '%H:%M'), 
         tm2 = if_else(tm1 > tm2, tm2 + 86400, tm2), 
         midtime = tm1 + difftime(tm2, tm1, units = 'secs')/2, 
         across(c(starts_with('tm'), midtime), format, '%H:%M'))

#  id   tm1   tm2 dur midtime
#1  1 23:00 07:00 8.0   03:00
#2  2 01:00 06:00 5.0   03:30

The logic is -

  • Convert tm1 and tm2 to POSIXct class. This will add today's date in both the columns.
  • Now if tm1 > tm2 (like in row 1) add 1 day to tm2 .
  • Subtract the two times, divide it by 2 and add the difference to tm1 to get midtime .
  • Finally change the time in '%H:%M' format in all columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM