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", ...
Creating a time seriesThe ts() function will convert a numeric vector into an R time series object. The format is ts(vector, start=, end=, frequency=) where start and end are the times of the first and last observation and frequency is the number of observations per unit time (1=annual, 4=quartly, 12=monthly, etc.).
1 Answer. If you have a dataframe named 'df' with DatetimeIndex, the following command will add a column labeled 'Timestamp' and the values corresponding to the values of the index: df['Timestamp'] = df. index.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With