[R] Kalman Filtering?

Spencer Graves spencer.graves at pdf.com
Wed Jun 15 17:36:51 CEST 2005


	  1.  The function "KalmanLike" seems to change its inputs AND 
PREVIOUSLY MADE copies of the inputs.  Consider the following (using R 
2.1.0 patched under Windows XP):

 > Fig2.1 <- StructTS(x=Nile, type="level")
 > unlist(Fig2.1$model0[2:3])
         a         P
      1120 286379470
 > tst2 <- tst <- Fig2.1$model0
 > tst23 <- tst[2:3]
 > tst23u <- unlist(tst23)
 > nile.KL <- KalmanLike(nile, tst2)
 > unlist(tst[2:3])
         a         P
  798.3682 4032.1469
 > unlist(tst2[2:3])
         a         P
  798.3682 4032.1469
 > unlist(Fig2.1$model0[2:3])
         a         P
  798.3682 4032.1469
 > unlist(tst23)
         a         P
  798.3682 4032.1469
 > tst23u
         a         P
      1120 286379470

	  "KalmanLike" changed attributes a and P of its input, tst2, as well 
as tst, from which tst2 was created, and Fig2.1$model0, from which tst 
was created:  Fig2.1$model0 was create by "StructTS" as a list that 
included components a = 1120 and P = 286379470.  When I called 
KalmanLike with a copy of a copy of that argument, KalmanLike changed 
all those copies plus one other, tst23.  The only copy that KalmanLike 
did NOT change was "unlisted", tst23u.  The function "KalmanLike" 
essentialy consists of a call to '.Call("KalmanLike", ...)', and I'm not 
eager to trace this behavior into that ".Call".  Would anyone care to 
comment on this behavior?

	  2.  I'm trying to recreate Figure 2.1 in Durbin and Koopman (2001), 
cited in the KalmanLike help file.  This figure consists of four panels, 
the first of which plots the Nile dataset with, apparently, the filtered 
state output by 'StructTS(x=nile, type="level")' and 'its 90% confidence 
interval".  The following is the code I used to try to recreate this 
figure:

Fig2.1 <- StructTS(x=Nile, type="level")
n.nile <- length(Nile)
cols <- c("filtered", "P", "s.e", "L.9", "U.9")
k <- length(cols)
#nile <- ts(nile., start=1871)
Nile. <- ts(array(c(fitted(Fig2.1), rep(NA, n.nile*(k-1))),
	dim=c(n.nile, length(cols)),
	dimnames=list(NULL, cols)), start=1871)

P <- Inf
h <- Fig2.1$model0$h
V <- Fig2.1$model0$V
for(i in 1:n.nile){
	P <- V+1/((1/P)+(1/h))
	Nile.[i, "P"] <- P
}

s2 <- KalmanLike(nile, Fig2.1$model0)$s2
Fig2.1 <- StructTS(x=Nile, type="level")

Nile.[, "s.e"] <- sqrt(s2*Nile.[, "P"])
z.9 <- qnorm(.95)
Nile.[, "L.9"] <- (Nile.[, "filtered"]-z.9*Nile.[, "s.e"])
Nile.[, "U.9"] <- (Nile.[, "filtered"]+z.9*Nile.[, "s.e"])

plot(nile)
lines(fitted(Fig2.1), lwd=2)
lines(Nile.[,"L.9"], col=2, lwd=2)
lines(Nile.[,"U.9"], col=2, lwd=2)

	  Does anyone have any comments on this?  The data for 1892, 1894, and 
1897 seem slightly outside the 90% confidence interval in Durbin and 
Koopman (2001, Fig. 2.1) but just inside the figure created by this code.

	  Am I doing this correctly?  Is there an easier way?

	  Thanks,
	  spencer graves




More information about the R-help mailing list