library(KFAS)
#Example of multivariate local level model
#Two series of average global temperature deviations for years 1880-1987
#See Shumway and Stoffer (2006), p. 327 for details
data(GlobalTemp)
yt<-array(GlobalTemp,c(2,108))
#Estimating the variance parameters
likfn<-function(par, yt, a1, P1, P1inf) #Function to optim
{
L<-matrix(c(par[1],par[2],0,par[3]),ncol=2)
H<-L%*%t(L)
q11<-exp(par[4])
lik<-kf(yt = yt, Zt = matrix(1,nrow=2), Tt=1, Rt=1, Ht=H, Qt=q11, a1 =
a1, P1=P1, P1inf=P1inf, optcal=c(FALSE,FALSE,FALSE,FALSE))
lik$lik
}
est<-optim(par=c(.1,0,.1,.1), likfn, method="BFGS",
control=list(fnscale=-1), hessian=TRUE, yt=yt, a1=0, P1=0, P1inf=1)
#Diffuse initialisation
pars<-est$par
L<-matrix(c(pars[1],pars[2],0,pars[3]),ncol=2)
H<-L%*%t(L)
q11<-exp(pars[4])
kfd<-kf(yt = yt, Zt = matrix(1,nrow=2), Tt=1, Rt=1,
Ht=H, Qt=q11, a1 = 0, P1=0, P1inf=1)
ksd<-ks(kfd)
#Same as non-diffuse, initial values from Shumway and Stoffer (2006):
est<-optim(par=c(.1,0,.1,.1), likfn, method="BFGS",
control=list(fnscale=-1), hessian=TRUE, yt=yt, a1=-0.35, P1=0.01, P1inf=0 )
pars<-est$par
L<-matrix(c(pars[1],pars[2],0,pars[3]),ncol=2)
H<-L%*%t(L)
q11<-exp(pars[4])
kfnd<-kf(yt = yt, Zt = matrix(1,nrow=2), Tt=1, Rt=1, Ht=H, Qt=q11, a1 =
-0.35, P1=0.01, P1inf=0)
ksnd<-ks(kfnd)
kfd$Qt
kfnd$Qt
kfd$Ht
kfnd$Ht
#Estimated Qt and Ht differs
#smoothed values:
ts.plot(ts(yt[1,],start=1880),ts(yt[2,],start=1880),ts(ksd$ahat[1,],start=1880),ts(ksnd$ahat[1,],start=1880),col=c(1,2,3,4))
Run the code above in your browser using DataLab