查找时间变量的均值和标准差,在 R 中考虑午夜过后的时间 [英] Finding the Mean and SD of time variables, taking times past midnight into account in R

查看:30
本文介绍了查找时间变量的均值和标准差,在 R 中考虑午夜过后的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚如何计算就寝时间的平均值和标准差,但我在管理午夜之后的时间很困难.这些概念在逻辑上是有道理的(我认为),但弄清楚如何在 R 中对其进行编码很棘手.

I am trying to figure out how to take the mean and SD of bedtimes, but I am having difficulty managing times after midnight. These concepts make sense logically (I think) but figuring out how to code it in R is tricky.

现在,那些将平均值拉向白天(即,向中午)的人,从逻辑上讲,他们应该将平均值拉向夜间(即,向午夜).

Right now, those pull the mean down toward daytime (i.e., toward noon), when they logically should pull the mean toward nighttime (i.e., toward midnight).

这是一个示例,其中平均时间应该更接近午夜,但事实并非如此.

Here is an example, where the mean time should be closer to midnight but isn't.

library(chron)
In.Bed.Date <- c("6/15/2019", "6/15/2019", "6/16/2019", "6/17/2019", "6/17/2019", "6/19/2019")
In.Bed.Time <- c("12:50 AM", "7:22 PM",  "5:20 PM",  "12:52 AM", "9:39 PM",  "1:00 AM")

#Fix In Bed Date/Time Variables
In.Bed.Date <- as.dates(In.Bed.Date)
In.Bed.Time <- as.times(format(strptime(In.Bed.Time, '%I:%M %p'), format = '%H:%M:%S'))

#New Combined Date/Time Variable for Bed
In.Bed <- chron(dates. = In.Bed.Date, times. = In.Bed.Time, format = c(dates = 'm/d/y', times = 'h:m:s'))

#Mean/SD just using Time variable
Mean <- mean(In.Bed.Time)
SD <- times(sd(In.Bed.Time))

#Mean/SD trying to use Date/Time variable
Mean <- mean(In.Bed)
SD <- times(sd(In.Bed))

我遇到的问题是使用 Time 变量的平均值在上午 10:10:30 出现.我认为 SD 也错误地格式化了时间变量,因为它显示为 10:15:06,但我对此不太确定.

The issues I am having is that the mean using the Time variable is coming out at 10:10:30 am. I think the SD is also incorrectly formatting the time variable, as it is coming out as 10:15:06, but I'm less sure about that.

尝试使用日期/时间变量会导致计算包含日期,这也不是我想要的.相反,我只想找到每晚的平均就寝时间,以及就寝时间的 SD.

Trying to use the Date/Time variable causes the calculation to include the date, which is also not what I want. Instead, I just want to find the average bedtime each night, and the SD of bedtimes.

推荐答案

为什么不直接添加 12 小时来计算平均值和标准偏差,然后减去 12 以恢复您的时间.像这样:

Why don't you just add 12 hours to calculate the mean and standard deviation and then subtract 12 to get your times back. Like this:

这是你自己的代码

In.Bed.Time <- c("12:50 AM", "7:22 PM",  "5:20 PM",  "12:52 AM", "9:39 PM",  "1:00 AM")
In.Bed.Time <- as.times(format(strptime(In.Bed.Time, '%I:%M %p'), format = '%H:%M:%S'))
In.Bed.Time
[1] 00:50:00 19:22:00 17:20:00 00:52:00 21:39:00 01:00:00

我建议你这样做

In.Bed.Time = In.Bed.Time + as.times('12:00:00')
Mean = mean(In.Bed.Time)
SD = sd(In.Bed.Time)
Mean
[1] 22:10:30
SD
[1] 0.4271581

然后你又回到原来的时间

And you get your original times back

In.Bed.Time = In.Bed.Time - as.times('12:00:00')
In.Bed.Time
[1] 00:50:00 19:22:00 17:20:00 00:52:00 21:39:00 01:00:00

这篇关于查找时间变量的均值和标准差,在 R 中考虑午夜过后的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆