I'm able to find a lot of info on SO regarding handling subsetting dates to a certain weekday (e.g. Get Dates of a Certain Weekday from a Year in R). However, I am unable to find any that implement a fallback logic that I'd like. Specifically, if a given weekday does not exist in a given week, I'd like to grab the next available date, excluding Saturday and Sunday.
For example, from a vector of dates, I want to select all dates corresponding to Thursdays. However, in weeks where Thursdays are missing, I should instead pick the date of the next working day. In the example below, this is the following day, the Friday.
library(lubridate)
# Create some dates
dates <- seq.Date(as.Date("2017-11-16"), as.Date("2017-11-24"), by = 1)
# Remove Thursday, November 23
dates <- dates[dates != as.Date("2017-11-23")]
# Get all Thursdays in dates
dates[wday(dates) == 5]
# [1] "2017-11-16"
# Desired Output:
# Because Thursday 2017-11-23 is missing in a week,
# we roll over and select Friday 2017-11-24 instead
# [1] "2017-11-16" "2017-11-24"
Note 1: For a given week where Thursday is missing and Friday is missing as well, I'd want to roll over to Monday. Essentially, for weeks where a Thursday is not found, grab the next date among the available dates.
Note 2: I'd like to accomplish this without any external dependencies other than common R packages such as lubridate, etc. (e.g. no dependency on a c++ library).
I'm confident I could write something to do what I want, but I am having trouble finding of creating something short and elegant.