我正在尝试对大于24小时的时间值进行计算。在这个简短的示例中,我试图根据某人的就寝时间和起床时间来计算他们的睡眠时间。但是,如果就寝时间是午夜之后,则以大于24小时的时间值输入数据。例如,如果某人凌晨2点入睡,则其睡前时间值为26:00:00。如何在R中处理大于24小时的时间值?
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 - bedtimeAsTimechron函数不接受大于24小时的时间值并将其转换为NA。有关如何处理此问题的任何想法?
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?
谢谢!
推荐答案我确定已经有一个软件包可以执行此操作,但是您可以使用 strsplit 和 as.numeric 。
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更多推荐
在R中使用大于24小时的时间值
发布评论