Data elements aren't transferring to my matrix. What's wrong?

49 views Asked by At

I made an empty matrix to populate with time series data and forecasts using

pred <- matrix(rep(NA,80),20,4)

But when I try to populate the matrix with a for loop, I get error message ("Error in pred[i, 2] <- forecast(fit.season, h = 1) : number of items to replace is not a multiple of replacement length")

beer1 <- window(ausbeer, start=1990,end=c(2009,4))
n.end <- 2004.75 # 2004Q4

fit.season <- tslm(beer1 ~ season, data=beer1)
fit.trend <- tslm(beer1 ~ season + trend, data=beer1)

for(i in 1:20){
  tmp0 <- 1990
  tmp1 <- n.end+(i-1)*.25
  tmp <- window(beer1,tmp0,tmp1)
  pred[i,1] <- window(beer1,tmp1+.25,tmp1+.25) # actual data
  # compute forecasts
  pred[i,2] <- forecast(fit.season, h=1)
  pred[i,3] <- forecast(fit.trend, h=1)
}

I know that the error message means the columns aren't equal so I checked the matrix and only the first element (row 1, column 1) was populated.

And my window seems okay so I tried with another set of functions in the loop.

for(i in 1:20){
  tmp0 <- 1992
  tmp1 <- n.end+(i-1)*.25
  tmp <- window(beer1,tmp0,tmp1)
  pred[i,1] <- window(beer1,tmp1+.25,tmp1+.25) # actual 
  # compute forecasts
  pred[i,2] <- meanf(tmp, h=1)$mean
  pred[i,3] <- rwf(tmp, h=1)$mean
  pred[i,4] <- snaive(tmp, h=1)$mean
}

And the whole matrix was populated.

What's wrong with the one I initially did?

1

There are 1 answers

3
Rob Hyndman On

The forecast function returns an object of class forecast, not a vector. Replace the last two lines in your loop by

pred[i,2] <- forecast(fit.season, h=1)$mean
pred[i,3] <- forecast(fit.trend, h=1)$mean

to extract just the point forecasts