我想生成一个包含指定范围内所有工作日的时间序列:
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)
此外,您可以使用format
来获得与chron
相同的结果:
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
。