Search code examples
rtime-seriesforecast

Forecast multiple time-series in R using


Consider an random data.frame:

d <- data.frame(replicate(10,sample(0:1,1000,rep=TRUE)))

I want to consider each row as a unique time-series (in this case for ten years). So first, I need to transform the data to time-series. I have tried the following code:

d1 <- ts(d, start=2000, end=2009)

However, this code consider the time-series as one long time-series for 100 years I think. In my case I want 1,000 unique time-series for 10 years.

And then I want to forecast each 1,000 time-series (let's say 1 year). By using the following code:

fit <- tslm(d1~trend) fcast <- forecast(fit, h=1) plot(fcast)

I get one forecast (since I in my dataset, d1, only consider one time-series).

Can anyone help me with this?


Solution

  • If we are looking for creating time series for each column, then loop through the columns of the dataset with lapply and create it

    library(forecast)
    lst1 <- lapply(d, ts, start = 2000, end = 2009)
    #If we want to split by `row`
    #lst1 <- lapply(asplit(as.matrix(d), 1), ts, start = 2000, end = 2009)
    par(mfrow = c(5, 2))
    lapply(lst1, function(x) {
            fit <- tslm(x ~ trend)
            fcast <- forecast(fit, h = 1)
            plot(fcast)
       })
    

    enter image description here