计算 R 中就寝时间 (hh:mm) 的平均值和标准差 - 问题是午夜之前/之后的时间 [英] Calculating mean and sd of bedtime (hh:mm) in R - problem are times before/after midnight
问题描述
我得到了以下数据集:
data <- read.table(text="
wake_time sleep_time
08:38:00 23:05:00
09:30:00 00:50:00
06:45:00 22:15:00
07:27:00 23:34:00
09:00:00 23:00:00
09:05:00 00:10:00
06:40:00 23:28:00
10:00:00 23:30:00
08:10:00 00:10:00
08:07:00 00:38:00", header=T)
我使用 chron-package 来计算平均唤醒时间:
I used the chron-package to calculate the average wake_time:
> mean(times(data$wake_time))
[1] 08:20:12
但是当我对变量 sleep_time 做同样的事情时,就会发生这种情况:
But when I do the same for the variable sleep_time, this happens:
> mean(times(data$sleep_time))
[1] 14:04:00
我猜结果是扭曲的,因为 sleep_time 包含午夜前后的时间.
I guess the result is distorted because the sleep_time contains times before and after midnight.
但是我该如何解决这个问题?
But how can I solve this problem?
另外:如何计算时间的标准差.我想像平均唤醒时间 08:20 ± 44 分钟"一样使用它例如.
Additionally: How can I calculate the sd of the times. I want to use it like "mean wake-up-time 08:20 ± 44 min" for example.
提前致谢,感谢您的帮助.
Thanks in advance, I appreciate any kind of help.
干杯
推荐答案
时间值存储为数字 0-1,代表一天的一小部分.如果睡眠时间早于醒来时间,可以加一天";在取平均值之前.例如
THe times values are stored as numbers 0-1 representing a fraction of a day. If the sleep time is earlier than the wake time, you can "add a day" before taking the mean. For example
library(chron)
wake <- times(data$wake_time)
sleep <- times(data$sleep_time)
times(mean(ifelse(sleep < wake, sleep+1, sleep)))
# [1] 23:40:00
而且由于这些值是一天的一部分,如果您想要以分钟为单位的 sd,您可以取部分日期值并转换为分钟
And since the values are parts of a day, if you want the sd in minutes, you'd take the partial day values and convert to minutes
sd(ifelse(sleep < wake, sleep+1, sleep) * 24*60)
# [1] 47.60252
这篇关于计算 R 中就寝时间 (hh:mm) 的平均值和标准差 - 问题是午夜之前/之后的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!