简体   繁体   中英

Get vector of Tuesdays, but if Tuesday falls on a holiday, then replace it with Wednesday in R

I would like to find all of the Tuesdays between two dates. But if the Tuesday falls on a user-defined list of holidays, then I would like Wednesday instead.

This code works in my tests, but it is pretty janky and I am afraid it will fail silently.

low.date <- "1996-01-01"
high.date <- "1997-01-01"
holidays = c("01-01", "07-04", "12-25")
tues <- seq(as.Date(low.date), as.Date(high.date), by = 1) 
tues <- subset(tues, format(tues, "%a") == "Tue")
tues <- ifelse(format(tues, "%m-%d") %in% holidays, tues + 1, tues)
tues <- as.Date(tues, origin = "1970-01-01")

Thanks! I see answers pointing to the timeDate package, but I only see methods for finding business days or holidays. Is there a cleaner/safer logic than what I'm using?

It's difficult to modify the logic of your solution. But here is a different form using wday function from lubridate package.

hol_tue <-  wday(tues) == 3L & format(tues, "%m-%d") %in% holidays
wday(tues)[hol_tue] <- 4

Slightly inconveniently in lubridate package day count starts from Sunday with Sunday being day 1 as opposed to POSIXlt where it's 0.

POSIXlt in the base package gives you access to wday as a number, which is a little safer since names of days change from system to system.

low.date <- "1996-01-01"
high.date <- "1997-01-01"
holidays <- c("01-01", "07-04", "12-25")

all.days <- seq(as.Date(low.date), as.Date(high.date), by = "day")

# Tuesday is Day 2 of the week
all.tues <- all.days[as.POSIXlt(all.days)$wday == 2]
tues.holidays <- format(all.tues, "%m-%d") %in% holidays
all.tues[tues.holidays] <- all.tues[tues.holidays] + 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM