Last active
February 3, 2022 19:28
-
-
Save plnnr/0a2c0206f7521598ba1ead9daf02acfd to your computer and use it in GitHub Desktop.
Return an integer of the number of weekdays in a month before or after a specified input date. Helpful for transit planning and NTD reporting when a sign-up period is in a split month. I.E. when the operator and route schedules change in the middle of a month and you must compute a weighted average based on the number of days within a signup per…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## Returns an integer of the number of weekdays in a month before or after a specified input date | |
## Counts weekdays (M-F), weekends (Sat and Sun), Sat only or Sun only | |
## Borrowed code from @Thomas at link below: | |
## https://stackoverflow.com/questions/29252520/using-r-to-count-number-of-specific-days-in-a-specific-month | |
count_monthly_weekdays <- function(x, direction, weekday = "weekend", inclusive = FALSE){ | |
## x is the date from which to calculate remaining weekend days | |
## direction is whether you count before or after input date x | |
## weekday is the weekdays to count (saturday, sunday, both, weekday) | |
## inclusive T/F is whether to include the input date x in the days remaining | |
x <- as.Date(x) | |
last_day_of_month <- ceiling_date(x, "month")-1 | |
first_day_of_month <- floor_date(x, "month") | |
if(tolower(direction) == "after"){ | |
if(x == last_day_of_month & !inclusive){ | |
stop("Last day of month input. Specify inclusive = TRUE to include last day of month.") | |
} | |
if(!inclusive){x <- x + 1} | |
d <- days_in_month(x) | |
d2 <- x + (0:(d-day(x))) | |
} | |
if(tolower(direction) == "before"){ | |
if(x == first_day_of_month & !inclusive){ | |
stop("First day of month input. Specify inclusive = TRUE to include first day of month.") | |
} | |
if(!inclusive){x <- x - 1} | |
d2 <- (first_day_of_month-1) + (day(first_day_of_month):day(x)) | |
} | |
if(tolower(weekday) == "weekday"){ | |
return(sum(wday(d2) %in% c(2:6))) | |
} | |
if(tolower(weekday) %in% c("saturday", "sat")){ | |
return(sum(wday(d2) %in% c(7))) | |
} | |
if(tolower(weekday) %in% c("sunday", "sun")){ | |
return(sum(wday(d2) %in% c(1))) | |
} | |
if(tolower(weekday) == "weekend"){ | |
return(sum(wday(d2) %in% c(1,7))) | |
} | |
} | |
count_monthly_weekdays('2022-02-01', | |
direction = "before", | |
weekday = "weekday", | |
inclusive = TRUE) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment