Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain the last weekday in a month using lubridate

Tags:

r

lubridate

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

like image 404
Thomas Philips Avatar asked Dec 30 '25 21:12

Thomas Philips


1 Answers

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"
like image 143
zephryl Avatar answered Jan 02 '26 13:01

zephryl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!