我的表格中有一个润滑周期列,如下所示。
workerID worked_hours
02 08H30M00S
02 08H00M00S
03 08H00M00S
03 05H40M00S
我想要实现的效果就像是workerID工作的总小时数之和。而且我也希望它采用HH:MM:SS格式,即使小时数超过24,我也不希望它有一天,而是使小时数累计超过24。 我尝试过
df %>%
group_by(workerID) %>%
summarise(sum(worked_hours))
但这会返回0
。
答案 0 :(得分:0)
还有一个基本的R解决方案。我添加的行超过了几分钟和几小时。
workerID worked_hours
1 2 08H30M00S
2 2 08H00M00S
3 3 08H00M00S
4 3 05H40M00S
5 2 09H45M00S
我们可以在字符处分割worked_hours
,然后按工作人员的ID进行汇总。之后,我们需要从分钟数中减去整小时。最后,我们用:
来消磨时间。
p <- cbind(p[1], do.call(rbind, lapply(strsplit(p$worked_hours, "\\D"), as.numeric)))
p <- aggregate(. ~ workerID, p, sum)
p$`1` <- p$`1` + floor(p$`2` / 60)
p$`2` <- p$`2` %% 60
p[-1] <- lapply(p[-1], function(x) sprintf("%02d", x)) # to always have two digits
cbind(p[1], worked_hours=apply(p[-1], 1, function(x) paste(x, collapse=":")))
# workerID worked_hours
# 1 2 26:15:00
# 2 3 13:40:00
数据
p <- structure(list(workerID = c("2", "2", "3", "3", "2"), worked_hours = c("08H30M00S",
"08H00M00S", "08H00M00S", "05H40M00S", "09H45M00S")), row.names = c(NA,
-5L), class = "data.frame")
答案 1 :(得分:0)
您可以使用软件包lubridate
,该软件包使处理时间变得更加容易。对于您而言,我们需要先转换为hms
(小时数秒)类,并按工作人员ID分组,然后转换sum
。但是,为了以HH:MM:SS
格式获取它,我们需要将其转换为句点,即
library(tidyverse)
library(lubridate)
df %>%
mutate(new = as.duration(hms(worked_hours))) %>%
group_by(workerID) %>%
summarise(sum_times = sum(new)) %>%
mutate(sum_times = seconds_to_period(sum_times))
给出,
# A tibble: 2 x 2 workerID sum_times <int> <S4: Period> 1 2 16H 30M 0S 2 3 13H 40M 0S