2

我想找到两个日期之间的所有星期二。但是,如果星期二属于用户定义的假期列表,那么我希望改为星期三。

这段代码在我的测试中有效,但它很笨拙,我担心它会默默地失败。

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")

谢谢!我看到指向timeDate包裹的答案,但我只看到查找工作日或假期的方法。有比我使用的更清洁/更安全的逻辑吗?

4

2 回答 2

4

很难修改解决方案的逻辑。但这里有一种不同的形式使用包中的wday函数lubridate

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

lubridate 包天数从周日开始,周日是第 1 天,而不是 POSIXlt 的第 0 天,这有点不方便。

于 2011-01-22T23:24:16.463 回答
2

基础包中的 POSIXlt 允许您以wday数字形式访问,这更安全一些,因为日期名称因系统而异。

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
于 2011-01-22T22:33:06.740 回答