Home > Blockchain >  How do I turn a date into a number representing the count of workdays in that month up to that date
How do I turn a date into a number representing the count of workdays in that month up to that date

Time:02-01

I have an array of dates. I need to convert these dates into their representing workday for their respective months. For example, 12/14/2021 (mm/dd/yyyy) must be turned into 10 because it is the 10th workday in the month of December of 2021; similarly, 1/31/2022 must be turned into 21 since it is the 21th workday in the month of January of 2022. If the date is not a workday, we can choose an identifying characters.

I thought about using the bizdays package but I'm struggling here. Could anyone help?

Thank you!

CodePudding user response:

Assuming we can forget about holidays, then we can use the following function:

business_day <- function(date) {
  vapply(date, function(d) {
    vec <- seq(lubridate::floor_date(d, "month"), d, by = "1 day")
    vec <- lubridate::wday(vec)
    length(which(vec > 1 & vec < 7))
  }, numeric(1))
}

This simply takes the sequence from the start of the month to the given date, and counts up all the days that aren't Saturdays or Sundays. It is vectorized so it can work on any given number of dates. For example:

dates <- as.POSIXct(c("2021-07-26", "2022-02-04", "1999-03-21"))

business_day(dates)
#> [1] 18  4 15

Created on 2022-01-31 by the reprex package (v2.0.1)

  •  Tags:  
  • Related