在“hr:min:sec 格式的列中的平均时间”问题中,给出了以下示例:
Col_Time = c('03:08:20','03:11:30','03:22:18','03:27:39')
library(chron)
mean(times(Col_Time))
[1] 03:17:27
如何获得 hr:min:sec 作为标准偏差的结果?如果我使用 R 函数sd,结果如下所示:
sd(times(Col_Time))
[1] 0.006289466
在“hr:min:sec 格式的列中的平均时间”问题中,给出了以下示例:
Col_Time = c('03:08:20','03:11:30','03:22:18','03:27:39')
library(chron)
mean(times(Col_Time))
[1] 03:17:27
如何获得 hr:min:sec 作为标准偏差的结果?如果我使用 R 函数sd,结果如下所示:
sd(times(Col_Time))
[1] 0.006289466
sd
正在对内部表示时间的数字进行操作(天为chron::times
,秒为hms
and POSIXct
,可设置为difftime
),这很好。唯一的问题是它正在从结果中删除该类,因此打印效果不佳。那么,解决方案就是在之后转换回时间类:
x <- c('03:08:20','03:11:30','03:22:18','03:27:39')
chron::times(sd(chron::times(x)))
#> [1] 00:09:03
hms::as.hms(sd(hms::as.hms(x)))
#> 00:09:03.409836
as.POSIXct(sd(as.POSIXct(x, format = '%H:%M:%S')),
tz = 'UTC', origin = '1970-01-01')
#> [1] "1970-01-01 00:09:03 UTC"
as.difftime(sd(as.difftime(x, units = 'secs')),
units = 'secs')
#> Time difference of 543.4098 secs
你可以使用lubridate
包。该hms
函数将时间从字符转换为HMS
格式。然后使用seconds
转换为秒并计算mean/sd
。最后,用于seconds_to_period
获取HMS
格式的结果。
library(lubridate)
Col_Time = c('03:08:20','03:11:30','03:22:18','03:27:39')
#Get the mean
seconds_to_period(mean(seconds(hms(Col_Time))))
# [1] "3H 17M 26.75S"
#Get the sd
seconds_to_period(sd(seconds(hms(Col_Time))))
#[1] "9M 3.40983612739285S"