开发者

Generating a time series with a specific start and end date

开发者 https://www.devze.com 2023-04-09 01:03 出处:网络
I want to generate a time series with all business dates in the range: startDate = \"1990-01-01开发者_运维百科\"

I want to generate a time series with all business dates in the range:

startDate = "1990-01-01开发者_运维百科"
endDate = "1990-12-31"

For example "1990-01-01", "1990-01-02", ...


@csgillespie: chron provides the function 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)

Besides, you can get the same results without chron using format:

isWeekend <- function(x) {format(x, '%w') %in% c(0, 6)}
weekDays2 = days[!isWeekend(days)]


You can just use the seq command. For example,

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

or

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

To just get business days, you can use the chron library:

days = seq(as.Date("1990-01-01"), as.Date("1990-12-31"), by="1 day")
library(chron)
weekDays = days[!is.weekend(days)]


There is a base function called ?weekdays.

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

But, since the actual names of the days will be locale-specific, be sure to set those correctly.

Note that weekdays is just a wrapper on format(x, "%A"). See ?strptime for the details on the format codes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号