Loop for a TS object: forecasting

Viewed 40

I have the next issue: I have a time-series object that has 30 rows and 20 columns. One of each column is a time-serie. The purpose is to forecast all the time-series (20). For that, I want to make a loop that contains a custom function application

The function is this one:

forecastMethods = function(x, h = 12){
  x = as_tsibble(x)
  mNaive = model(x, NAIVE())
  fNaive = forecast(mNaive, h = h)[, 4]
  mSnaive = model(x, SNAIVE())
  fSnaive = forecast(mSnaive, h = h)[, 4]
  mTheta = model(x, THETA())
  fTheta = forecast(mTheta, h = h)[, 4]
  mETS = model(x, ETS())
  fETS = forecast(mETS, h = h)[, 4]
  mARIMA = model(x, ARIMA())
  fARIMA = forecast(mARIMA, h = h)[, 4]
  aux = cbind(fNaive, fSnaive, fTheta, fETS, fARIMA)
  allF = cbind(aux, rowMeans(aux, na.rm = TRUE),
               rowMedians(aux, na.rm = TRUE),
               rowMedians(aux[, 3 : 5], na.rm = TRUE))
  colnames(allF) = c("Naive", "Snaive",
                     "Theta", "ETS", "ARIMA",
                     "MeanAll", "MedianAll",
                     "MedianSome")
  return(allF)
}

The data is not possible to copy here, because I can't reproduce it. I made a little example of the data:

s1 = c(664.3, 721.0, 815.3, 842.7, 938.4, 1091.4, 1145.8, 1229.8, 1281.1, 1438.2, 1514.0, 1618.5, 1609.0, 1794.8, 1852.7, 1968.9, 2093.9, 2169.0, 2244.8, 2417.4, 2470.5, 2590.7, 2550.3, 2544.7, 2628.1, 2740.4, 2920.5, 2873.2, 3109.9, 3254.7)

s2 = c(2476.15, 2787.32, 2764.33, 2546.98, 2868.88, 2990.70, 2953.76, 2965.39, 3113.72, 3234.62, 3373.75, 3306.09, 3396.52, 3472.33, 3593.75, 3442.01, 3507.12, 3624.23, 3648.89, 3642.36, 3878.79, 4000.28, 3904.80, 3941.63, 3901.86, 3866.70, 3943.48, 3885.86, 3854.16, 3502.24)

s3 = c(2340, 2560, 2860, 3150, 3360, 3410, 3580, 3960, 4220, 4440, 4740, 5260, 5710, 6060, 5950, 5950, 6200, 6190, 6760, 7650, 7580, 7350, 7820, 8570, 8640, 9190, 9480, 9670, 9750, 9740)

s1 <- as.ts(s1, start = 1989, end = 2018)
s2 <- as.ts(s2, start = 1989, end = 2018)
s3 <- as.ts(s3, start = 1989, end = 2018)

df <- as.data.frame(cbind(s1,s2,s3))

The loop has to forecast all the time series presented in the columns ob the object. I tried this one:

for(i in 1:20) {
  forecastMethods(df[,i], h = 6)
}

Thanks for the help!

0 Answers
Related