Working with time values greater than 24 hours in R

徘徊边缘 提交于 2020-01-14 14:57:09

问题


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!


回答1:


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



回答2:


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!



来源:https://stackoverflow.com/questions/17889948/working-with-time-values-greater-than-24-hours-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!