Search code examples
rdatelubridate

R - working days in a given week of a month


I am trying to get the working days of a given week on a given month.

This is my current data, as example:

year  month week
2020   6      1
2020   6      2
2020   6      3
2020   6      4
2020   6      5
2020   7      1
2020   7      2
2020   7      3
2020   7      4
2020   7      5

The expected result:

year  month week  work_days
2020   6      1      5
2020   6      2      5
2020   6      3      5
2020   6      4      5
2020   6      5      2
2020   7      1      3
2020   7      2      5
2020   7      3      5
2020   7      4      5
2020   7      5      5

So as you can see I have year, month and week of the month but I can't get my head around how to get the working days for the week in R for any week of any month.

Thanks in advance


Solution

  • cal <- data.table(dates = seq.Date(ymd(20200601), ymd(20200731), by = "day")) %>% 
            .[, .(dates, 
                  year = year(dates), 
                  month = month(dates), 
                  week = isoweek(dates),    # new week starts on monday 
                  weekday = !(weekdays(dates) %in% c("Sunday", "Saturday"))
             )] 
    
    cal[, .(work_days = sum(weekday)), by = .(year, month, week)
        ][, week := rowid(month)][]