繁体   English   中英

生成具有特定开始和结束日期的时间序列

[英]Generating a time series with a specific start and end date

我想生成一个包含该范围内所有业务日期的时间序列:

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

有一个名为?weekdaysbase功能。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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