2

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"))

Picture of data frame

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

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
R. R.
  • 33
  • 3
  • 1
    [Calculating mean and sd of bedtime (hh:mm) in R - problem are times before/after midnight](https://stackoverflow.com/questions/65637024/calculating-mean-and-sd-of-bedtime-hhmm-in-r-problem-are-times-before-after) – Henrik May 16 '21 at 12:46

2 Answers2

1

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.
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

you can just add half of the duration

format(strptime(dat$tm1,format = '%H:%M') + dat$dur*3600/2, format = '%H:%M')
dww
  • 30,425
  • 5
  • 68
  • 111