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)