如何在没有特定日期且不超过 24 小时的情况下使用 lubridate 添加小时数?

How to add hours with lubridate without specific dates, and not over 24h?

我正在尝试使用 lubridate 作为优化员工日程安排的基础。如何在不必在日历中使用特定日期的情况下为轮班和工作时间编写数据框? (是的,我刚刚开始,并且已经 运行 解决了简单的问题,我是 R 的新手...)

我手动写了一些信息,但我需要能够以 24 小时为基础进行计算,所以我尝试计算工作时间以确保确定。

shift <- c("week", "evening", "weeknight", "weekend", "weekendnight")
start <- c(hms::as.hms(27000), hms::as.hms(43200), hms::as.hms(77400), hms::as.hms(28800), hms::as.hms(72000))
end <- c(hms::as.hms(64800), hms::as.hms(79200), hms::as.hms(29700), hms::as.hms(72000), hms::as.hms(28800))
hours <- c(hms::as.hms(37800), hms::as.hms(36000), hms::as.hms(38700), hms::as.hms(43200), hms::as.hms(43200))


shiftsDF <- data.frame(shift, start, end, hours) %>%
mutate(computedhours = hms::as.hms(end-start)) 

我希望 "computedhours" 与我手动输入的 "hours" 相同,直到我明白它只是秒的总和,与日期无关。我怎样才能让 R studio 明白我说的是几天而不用使用确切的日期?

使用dplyr::if_else我们可以做到

library(lubridate)
library(dplyr)
data.frame(shift, start, end, hours) %>%
    mutate(computedhours = if_else(end < start, 
                                   hms::as.hms(dmy_hms(paste('02/01/2019',end)) - dmy_hms(paste('01/01/2019',start))),
                                   hms::as.hms(end-start)))

使用 difftime 的基本 R 方法是在 end 上添加一天(86400 秒),如果 start > end 并使用 difftime 在 [=16] 中获得输出=] 作为单位。

with(shiftsDF, ifelse(start > end, 
        difftime(as.POSIXct(end) + 86400, as.POSIXct(start), units = "hours") ,
        difftime(end, start, units=  "hours")))

#[1] 10.50 10.00 10.75 12.00 12.00

这个 returns 小时的比率,其中 10.5 表示 10 小时 30 分钟,10.75 表示 10 小时 45 分钟,依此类推。

数据

shiftsDF <- data.frame(shift, start, end, hours)