Day 19: year_month_weekday()

Get the nth occurrence of a given weekday in a month with clock’s year_month_weekday() function.
Published

December 19, 2022

Scheduling things is hard. With the exception of February (assuming it’s not a leap year), the number of days in a month isn’t even divisible by number of days in a week. So, if you’re on a committee that meets once a month, you probably don’t meet on the same numerical date each month, but, rather the nth occurrence of a given weekday. This is how most federal holidays are scheduled in the United States1. American Thanksgiving, for example, takes place on the fourth Thursday in November.

So, how do we figure out when that is in terms of date? Well, the clock (Vaughan 2022) package has you covered with the year_month_weekday() function.

year_month_weekday() constructs a calendar vector from the Gregorian year, month, weekday, and index specifying that this is the n-th weekday of the month.

Let’s use it to figure out when Thanksgiving will be in 2023. The arguments for things like months and weekdays are meant to be integers, but clock has integer codes mapping the names to numbers, which I’ll make use of. To print it as an actual date (as opposed to the returned year-month-weekday calendar vector), we’ll use as_date().

library(clock)

x <- year_month_weekday(
  year = 2023, 
  month = clock_months$november, 
  day = clock_weekdays$thursday,
  index = 4
)

x
#> <year_month_weekday<day>[1]>
#> [1] "2023-11-Thu[4]"

x |> as_date()
#> [1] "2023-11-23"

References

Vaughan, Davis. 2022. clock: Date-Time Types and Tools. https://clock.r-lib.org.