Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing up periods

Tags:

date

r

lubridate

I have a lubridate period column in my table as the following shows.

workerID   worked_hours
02         08H30M00S
02         08H00M00S    
03         08H00M00S
03         05H40M00S

What I want to achieve is like sum the number of hours worked by workerID. And I also want it to be in the HH:MM:SS format, even if the hours exceed 24, I dont want it to have the day and instead have the hours accumulate to more than 24. I have tried working with

df %>%
 group_by(workerID) %>% 
 summarise(sum(worked_hours))

but this returns a 0.


1 Answers

You can use the package lubridate which makes dealing with times a bit easier. In your case, we need to convert to hms (hours minutes seconds) class first, group by worker ID and take the sum. However, in order to get it in the format HH:MM:SS, we need to convert to period, i.e.

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))

which gives,

# A tibble: 2 x 2
   workerID sum_times   
     <int> <S4: Period>
1        2 16H 30M 0S  
2        3 13H 40M 0S
like image 169
Sotos Avatar answered Oct 18 '25 22:10

Sotos