2011-01-22 14 views
2

我想查找兩個日期之間的所有星期二。但如果星期二屬於用戶定義的節假日列表,那麼我希望星期三。獲取星期二的矢量,但是如果星期二是假期,那麼用星期三替換它在R

這段代碼適用於我的測試,但它很笨拙,我恐怕會失敗。

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包的答案,但我只能看到找到工作日或節假日的方法。有沒有比我使用的更清潔/更安全的邏輯?

+0

只是一個小評論,但重新使用變量`tues`一樣,這將使它很難測試。如果第二個賦值出現錯誤,比如說,它會在最後被覆蓋兩次,所以很難追溯。 – 2011-01-22 23:43:15

+0

@G - 好的電話。謝謝。有時候我認爲我在保存RAM,但在這種情況下這很荒謬。 – 2011-01-23 14:42:02

回答

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 
+0

這似乎比海報的解決方案更糟糕。 – 2011-01-22 22:59:30

4

很難修改解決方案的邏輯。但是這裏使用lubridate包的wday函數是一種不同的形式。

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

稍微不便在lubridate包天數從星期日開始以週日爲1天,而不是POSIXlt它是0

相關問題