Search code examples
rdatetimetime-seriesforecasting

R function to return start & end date of a time series ts() object?


I have created a list of 300 time series.

Now I want to create a training sample(by holding out most recent 3 weeks) for each of the time series to build forecast models. So I want to use window function to subset the time series to skip the most recent 3 weeks as shown below.

# Creating training data
train_ts<-lapply(ts_list, function(x){
  window(x,start=c(start_year,start_month),end=c(.....,.....))
}
)

But the problem is that the end date of each of the time series is different.

So to help me achieve this, is there a R function which will return the start and end values of a ts object?

I searched in this website by couldn't find a solution. Thanks


Solution

  • Here is a simple example assuming weekly data:

    x <- ts(rnorm(200), frequency=52)
    endx <- end(x)
    window(x, end=c(endx[1],endx[2]-3))
    

    Of course, there are not actually 52 weeks in a year, but that is probably a complication that can be overlooked for most analyses.