I'm trying to get the last weekday of a month using lubridate. I tried writing
> lubridate::ceiling_date(as.Date("2023-12-22"), 'month') - lubridate::wday(1)
[1] "2023-12-31"
but I get the last day of the month, which in this case is a Sunday. I could write a function with a loop that keeps incrementing the argument of wdays() till I hit a weekday, but there must be a simpler way.
Sincerely with many thanks in advance
Thomas Philips
This function generates the last three days in the month, then filters to weekdays and takes the max. (Thanks to @r2evans for pointing out we only need the last three days rather than all days in the month.)
library(lubridate)
last_weekday <- function(x) {
last_days <- ceiling_date(x, "month") - days(1:3)
max(last_days[wday(last_days, week_start = 1) < 6])
}
last_weekday(as.Date("2023-12-22"))
# [1] "2023-12-29"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With