Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a time series with a specific start and end date

Tags:

date

time

range

r

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", ...

like image 228
Eva Avatar asked Sep 29 '11 09:09

Eva


People also ask

How do you convert a time series to a date?

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

How do I index a date in python?

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.


3 Answers

@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)]
like image 156
Oscar Perpiñán Avatar answered Nov 01 '22 08:11

Oscar Perpiñán


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)]
like image 36
csgillespie Avatar answered Nov 01 '22 06:11

csgillespie


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.

like image 2
mdsumner Avatar answered Nov 01 '22 08:11

mdsumner