【发布时间】:2011-11-27 13:47:06
【问题描述】:
我想生成一个包含范围内所有营业日期的时间序列:
startDate = "1990-01-01"
endDate = "1990-12-31"
例如“1990-01-01”、“1990-01-02”、...
【问题讨论】:
我想生成一个包含范围内所有营业日期的时间序列:
startDate = "1990-01-01"
endDate = "1990-12-31"
例如“1990-01-01”、“1990-01-02”、...
【问题讨论】:
@csgillespie:chron提供函数is.weekend:
days = seq(as.Date("1990-01-01"), as.Date("1990-12-31"), by="1 day")
library(chron)
weekDays = days[!is.weekend(days)]
## let's check the result with the function weekdays
weekdays(weekDays)
此外,您可以在不使用chron 的情况下使用format 获得相同的结果:
isWeekend <- function(x) {format(x, '%w') %in% c(0, 6)}
weekDays2 = days[!isWeekend(days)]
【讨论】:
您可以只使用seq 命令。例如,
##Specify you want 10 dates starting on 1990-01-01
R> seq(as.Date("1990-01-01"), length.out=10, by="1 day")
[1] "1990-01-01" "1990-01-02" "1990-01-03" "1990-01-04" "1990-01-05"
[6] "1990-01-06" "1990-01-07" "1990-01-08" "1990-01-09" "1990-01-10"
或
##Specify the start and end with increment
R> seq(as.Date("1990-01-01"), as.Date("1990-01-10"), by="1 day")
[1] "1990-01-01" "1990-01-02" "1990-01-03" "1990-01-04" "1990-01-05"
[6] "1990-01-06" "1990-01-07" "1990-01-08" "1990-01-09" "1990-01-10"
要获得工作日,您可以使用chron 库:
days = seq(as.Date("1990-01-01"), as.Date("1990-12-31"), by="1 day")
library(chron)
weekDays = days[!is.weekend(days)]
【讨论】:
有一个名为?weekdays 的base 函数。
startDate = "1990-01-01"
endDate = "1990-12-31"
x <- seq(as.Date(startDate), to = as.Date(endDate), by="1 day")
x[!weekdays(x) %in% c("Sunday", "Saturday")]
但是,由于日期的实际名称会因地区而异,因此请务必正确设置这些名称。
请注意,weekdays 只是 format(x, "%A") 的包装。有关格式代码的详细信息,请参阅?strptime。
【讨论】: