You were most of the way there.
I wrote a little helper function called normTimes
to convert your times with hours greater than 23, and then just subtracted one from sleepDuration where it exceeded one.
require(chron)
bedtime <- c("22:37:34","23:03:32","24:41:23")
waketime <- c("06:41:23","07:25:18","08:47:08")
normTimes <- function(Tt)
{
hourFun <- function(hrs)
{
if(nchar(hrs) == 1)
{
paste0(0, hrs, substr(tt, 3, 8))
} else {
paste0(hrs, substr(tt, 3, 8))
}
}
tt <- Tt[substr(Tt, 1, 2) > 23]
adjt <- as.numeric(substr(tt, 1, 2)) - 23
Tt[substr(Tt, 1, 2) > 23] <- sapply(adjt, hourFun)
return(Tt)
}
bedtime <- normTimes(bedtime)
bedtimeAsTime <- chron(times=bedtime) #no longer results in an error
waketimeAsTime <- chron(times=waketime)
#Add 24 hours
waketimeAsTime <- waketimeAsTime + 1
sleepDuration <- waketimeAsTime - bedtimeAsTime
sleepDuration[sleepDuration > 1] <- sleepDuration[sleepDuration > 1] - 1
(sleepDuration)
[1] 08:03:49 08:21:46 07:05:45
And there you have it!