r - 如何在 R 中求和或平均小时数

标签 r time hour lubridate

为什么 sum 和 average 不适用于使用 lubridate 提取的小时数,而使用 + 和除法的简单加法可以单独工作。

数据集

Category   Time1    Time2       hr1        hr2
1        A 0:30:00 24:00:00    30M 0S  24H 0M 0S
2        B 1:00:00 23:23:00  1H 0M 0S 23H 23M 0S
3        C 2:30:00 23:00:59 2H 30M 0S 23H 0M 59S
4        D 3:00:00 45:00:00  3H 0M 0S  45H 0M 0S

> dput(t1)
structure(list(Category = c("A", "B", "C", "D"), Time1 = c("0:30:00", 
"1:00:00", "2:30:00", "3:00:00"), Time2 = c("24:00:00", "23:23:00", 
"23:00:59", "45:00:00"), hr1 = structure(c(0, 0, 0, 0), year = c(0, 
0, 0, 0), month = c(0, 0, 0, 0), day = c(0, 0, 0, 0), hour = c(0, 
1, 2, 3), minute = c(30, 0, 30, 0), class = structure("Period", package = "lubridate")), 
    hr2 = structure(c(0, 0, 59, 0), year = c(0, 0, 0, 0), month = c(0, 
    0, 0, 0), day = c(0, 0, 0, 0), hour = c(24, 23, 23, 45), minute = c(0, 
    23, 0, 0), class = structure("Period", package = "lubridate"))), .Names = c("Category", 
"Time1", "Time2", "hr1", "hr2"), row.names = c(NA, -4L), class = "data.frame")

注册码
t1<-read.csv("time1.csv", header=TRUE, sep=",",stringsAsFactors=FALSE)
library(lubridate)
t1$hr1<-hms(t1$Time1)
t1$hr2<-hms(t1$Time2)

#这个作品
> t1$hr1[4]+t1$hr2[3]
[1] "26H 0M 59S"

> (t1$hr1[4]+t1$hr2[3])/2
[1] "13H 0M 29.5S"

但这不是
> sum(t1$hr1[4]+t1$hr2[3])
[1] 59

> mean(t1$hr1[4]+t1$hr2[3])
[1] 59

最佳答案

您可以使用 period_to_seconds要转换为秒,请执行 summean ,然后 seconds_to_period转换回 period .

library(lubridate)
t1$hr1 = hms(t1$Time1)
t1$hr2 = hms(t1$Time2)

fsum = function(...){
    seconds_to_period(sum(period_to_seconds(...)))
}
fmean = function(...){
    seconds_to_period(mean(period_to_seconds(...)))
}
tohms = function(...){
    ans = c(...)
    ans@hour = ans@day*24 + ans@hour
    ans@day = 0
    ans
}

t2 = fsum(t1$hr1[4]+t1$hr2[3])
t2
#> [1] "1d 2H 0M 59S"

tohms(t2)
#> [1] "26H 0M 59S"

如果您预计 summean要超过一年(大约 365.25 天),您可能需要进行进一步的调整。

数据
t1 = structure(list(Category = c("A", "B", "C", "D"),
                    Time1 = c("0:30:00", "1:00:00", "2:30:00", "3:00:00"),
                    Time2 = c("24:00:00", "23:23:00", "23:00:59", "45:00:00")),
               class = "data.frame", row.names = c("1", "2", "3", "4"))

关于r - 如何在 R 中求和或平均小时数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29334489/

相关文章:

R 在 colname 中使用 get()

r - map-ggplot2 上的比例尺和指北针

ios - 如何调试具有时间依赖性的iOS应用

ios - 检查 Objective-c 中的时间?

r - 计算 R 中的平均时间

sql - 如何在 SQL Server 中生成两个小时之间的小时数?

r - 单击下载按钮后如何关闭 Shiny 的模式框

c# - 耗时/秒表

mysql - 如何显示计算的休假时间?

r - 按组查找向量中最频繁的组合