I am working through example 3.2.6 in 'Dynamic linear models with R' by Petris. I have download the USA GDP data located here: http://definetti.uark.edu/dlm/

The example starts by estimating the unknown parameters. See the code below:


# 1. read in data from Petris' website
gdp_ <-read.table("GDP.dat", header=TRUE, skip=12)
gdp<- ts(gdp_, frequency = 4, start =1950, end = 2004)

#2. plot log of time series
plot(log_gdp[,2], xlab = '', ylab = 'log US GDP', type = 'l')

#3. compute the MLE of the unknown parameters

buildGap<- function(u){
  trend <- dlmModPoly(dV = 1e-7, dW= exp(u[1:2]), m0=c(level0, slope0), C0=2*diag(2))
  gap   <- dlmModARMA(ar=u[4:5], sigma2=exp(u[3]))
  return<- (trend+gap)

outMLE<-dlmMLE(log_gdp, init, buildGap)

My questions are:

  • Do I need to fit an arima model to the data first and work out p,d and q? (I can easily do this with auto.arima). I don't understand how I am meant to know what goes into the dlmModARMA part of the code above i.e. setting ar, ma and sigma2

  • I don't fully understand how I would change the content of buildGap if I wanted to look at a different time series (let's assume it's ARIMA i.e. also trend + ARMA)

This was the ONLY example I could find of a combined model (with dlmModPoly and dlmModARMA). I'm also really new to this and struggling massively, so any simple explanations would be much appreciated. Thanks!


1 Answer 1


Concerning the order of the model, yes, you have to fix it when you build the model. Often you do this trying different orders.

Concerning function buildGap, an explanation cannot be given in this short space. Basically, what it does is to replace values of parameters at the right spots. dlmMLE uses as inputs a time series (log_gdp), a set of initial values of the parameters (init) and a function that builds the model (buildGap). Then, starting at the initial values, dlmMLE iterates trying to optimize the likelihood. At each iteration, buildGap re-builds the model with the new set of parameter values, so the likelihood can be computed.

You have other examples in the book by Petris et al. and documentation. You have to understand what the code does and write a specialized build function similar to buildGap for each model you want. It is not as hard as it sounds, usually you only have to modify slightly what you have to test a new model.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.