2

I am trying to build a state space model in R using the dlm library but keep getting the "incompatible dimensions of matrices" error.

The specifications of the model I am trying to produce are as per below:

Yt = At + beta*Ft + et

Ft = phi1Ft-1 + phi2Ft-2 + vt

At = At-1 + wt

where Yt is the observable variable, At is the time varying coefficient modelled as a random walk and Ft is a latent factor which follows an AR(2) process.

I have been trying to set up the FF, V, GG, W, m0 and C0 matrices required by dlm to specify the model, but have yet to get the program to work.

Please see below my latest attempt which returns an "incompatible dimensions of matrices" error.

I have traced the relative matrix sizes on paper and they look fine to me. Could anyone please advise where I am going wrong?

# the below code works now    
model <- function(x) {
  
  FF <- matrix(c(x[1],0,1), nr=1)
  V  <- matrix(exp(x[2]))
  
  GG <- matrix(c(x[3],1,0,x[4],0,0,0,0,1), nr=3)     
  W  <- diag(c(exp(x[5]),0,exp(x[6])))
  
  m0 <- rep(0,3)
  C0 <- 10*diag(3)
  
  dlm(FF=FF, V=V, GG=GG, W=W, m0=m0,C0=C0)
}
    
# x[1:6] are beta, Var(et), phi1, phi2, Var(vt) and Var(wt)

fit <- dlmMLE(y1, parm = c(rep(0,6)), build = model)

dlmy1 <- model(fit$par)
andrewJames
  • 19,570
  • 8
  • 19
  • 51
Stefan
  • 41
  • 4
  • Share the data for all the variables. I see x, x1, model, ... without data. Besides there is a lone `}` in the code. – Karthik Arumugham Feb 18 '17 at 16:21
  • Hi Karthik. Thanks for the reply. I updated the code and added some annotation. Hope it looks clearer now. Variables x[1:6] are parameters to be estimated in the model, while Y is a univariate data set I import from a spreadsheet. I hope to expand this to multivariate analysis in the future. Please let me know should you need more details and thanks again for looking into my post. – Stefan Feb 18 '17 at 16:57
  • 1
    Try replacing 1) `dlm(FF=FF, V=V, GG=GG, W=W, m0=m0,C0=C0)` with `return(list(FF=FF, V=V, GG=GG, W=W, m0=m0,C0=C0))` and 2) `fit <- dlmMLE(Y, parm = c(0,0,0,0), build = model)` with `fit <- dlmMLE(Y, parm = rep(0,6), build = model)` since there are six variables at play. I don't know the technical details of the operations, but this ought to work. – Karthik Arumugham Feb 18 '17 at 17:34
  • Thanks Khartik. I played around with the code as per your suggestions and managed to get it working. I updated the original post to reflect the changes made. Thanks again for your help. It is much appreciated. – Stefan Feb 19 '17 at 01:13

0 Answers0