rlubridatechron

Calculate midpoint for hh:mm variable over the span of two days with no date


I would like to calculate the midpiont between falling asleep and waking up. I'm struggling a bit, because I have no date, just the time as hh:mm.

For example, if you go to bed at 2 a.m. and wake up at 10 a.m., the midpoint is 6 a.m.

Below is an example and I'd be glad for some help!

DF <- data.frame(time_start = c("23:45", "21:30", "22:00", "23:00", "00:30", "02:00"),
                 time_end = c("06:49", "06:30", "07:00", "09:00", "5:30", "10:00"))

Solution

  • Convert the two time objects to numeric, calculate their averages, and then convert them back to time objects.

    library(dplyr)
    library(lubridate)
    
    DF %>%
      mutate_all(hm) %>%
      mutate(time_end = time_end + (time_end < time_start) * days(1),
             midpoint = seconds_to_period(as.numeric(time_start + time_end) / 2)) %>%
      mutate_all(~sprintf("%02d:%02d", hour(.), minute(.)))
    
    #   time_start time_end midpoint
    # 1      23:45    06:49    03:17
    # 2      21:30    06:30    02:00
    # 3      22:00    07:00    02:30
    # 4      23:00    09:00    04:00
    # 5      00:30    05:30    03:00
    # 6      02:00    10:00    06:00