Working with time values greater than 24 hours in R

date, date-arithmetic, r, time

Solution

I'm sure there's a package that does this already, but you can convert all these times to seconds using `strsplit` and `as.numeric`.

ConvertToSeconds <- function(X)
{
    X <- strsplit(X, ":")
    sapply(X, function(Y) sum(as.numeric(Y) * c(3600, 60, 1)))
}

bedtime <- ConvertToSeconds(bedtime)
waketime <- ConvertToSeconds(waketime) + (86400) #Seconds in 24 hours

sleeptime <- waketime-bedtime
sleeptime
[1] 29029 30106 29145

Problem

I'm trying to perform calculations on time values that are greater than 24 hours. In this short example, I'm trying to calculate someone's sleep duration based on their bedtime and waketime. If bedtime is after midnight, however, the data are entered as time values greater than 24 hours. For example, if someone went to sleep at 2am, their bedtime value is 26:00:00. How can I handle time values greater than 24 hours in R? Here's my short example attempt: ``` library(chron) bedtime <- c("22:37:34","23:03:32","24:41:23") waketime <- c("06:41:23","07:25:18","08:47:08") bedtimeAsTime <- chron(times=bedtime) #results in error waketimeAsTime <- chron(times=waketime) #Add 24 hours waketimeAsTime <- waketimeAsTime + 1 sleepDuration <- waketimeAsTime - bedtimeAsTime ``` The chron function does not accept the time value greater than 24 hours and converts it to NA. Any ideas for how to deal with this? Thanks in advance!

Original source