8

The R package dlm implements filtering and smoothing (dlmFilter and dlmSmooth) for models with regression effects, but forecasting is not (yet) available for these models:

mod <- dlmModSeas(4)+dlmModReg(cbind(rnorm(100),rnorm(100)))
fi <- dlmFilter(rnorm(100),mod)
f <- dlmForecast(fi,nAhead=12)
Error in dlmForecast(fi, nAhead = 12): 
  dlmForecast only works with constant models

How can I do this in R?

Thanks for your help!

Rob Hyndman
  • 51,928
  • 23
  • 126
  • 178

1 Answers1

7

Here's the solution I came up with: The trick is to add NAs to the end of the observation data. When seeing NA as a response variable the Kalman filter algorithm will simply predict the next value and not update the state vector. This is exactly what we want to make our forecast.

nAhead <- 12
mod <- dlmModSeas(4)+dlmModReg(cbind(rnorm(100+nAhead),rnorm(100+nAhead)))
fi <- dlmFilter(c(rnorm(100),rep(NA,nAhead)),mod)

Is this correct?

caas
  • 535
  • 1
  • 4
  • 7
  • Good idea, and it basically works. I suspect that there's a tradeoff of some sort -- otherwise the `dlm` folks could simply use that solution to code `dlmForecast` -- but it does basically work. – Wayne Sep 02 '11 at 18:53
  • How do I get updated forecast for dlmModReg with new data? If I re-run dlmFilter, it will re-estimate my model parameters. –  May 23 '16 at 08:16