[R] Using kfilter in package sspir - dimensions do not agree

John Dryden john.c.dryden at gmail.com
Tue Aug 24 19:22:56 CEST 2010


I'm currently running into a little trouble with the kfilter method,
and would love some clarification if you are able to offer it.  When
trying to run kfilter, I've been running into errors that seem to
result from having mismatched dimensions.  Specifically, the dimension
of my observations is 2, while the dimension of the state space is 4.
In the filterstep function (file sspir_kfs.R), this causes an error at
line 111: e <- y - f.  Vector y has dimension 4, while vector f has
dimension 2.  Here's some sample code:

######################################################################
require(sspir)

# getting the hang of the kalman filter
x.coords <- c(5,6,5,6,8,9,8,8,10,11)
y.coords <- c(25,30,42,51,55,52,42,28,24,31)
times <- 1:10
x.vel <- c(0,diff(x.coords)/diff(times))
y.vel <- c(0,diff(y.coords)/diff(times))
kal.df <- data.frame(x.coords,x.vel,y.coords,y.vel)
kal.ts <- ts(kal.df,deltat=mean(diff(times)))
my.Fmat <- function(tt,x,phi){
 mf <- matrix(c(1,0,0,0,0,1,0,0),nrow=4,byrow=T)
 return(mf)
}
my.Gmat <- function(tt,x,phi){
 mat <- matrix(c(1,x[[1]][tt],0,0,0,1,0,0,0,0,1,x[[1]][tt],0,0,0,1),nrow=4,byrow=T)
 return(mat)
}

my.Wmat <- function(tt,x,phi){
 row.1 <- c((x[[1]][tt]^4)/4,(x[[1]][tt]^3)/2,(x[[1]][tt]^4)/4,(x[[1]][tt]^3)/2)
 row.2 <- c((x[[1]][tt]^3)/2,x[[1]][tt]^2,(x[[1]][tt]^3)/2,x[[1]][tt]^2)
 mat <- rbind(row.1,row.2,row.1,row.2) # no need for as.matrix
 mat <- mat * phi[1]
 return(mat)
}
kal.SS <- SS(kal.ts,
           x=list(x=c(0,diff(times))),
           phi=0.5,
           Fmat=my.Fmat,
           Gmat=my.Gmat,
           Vmat=matrix(c(3,0,0,1),nrow=2,byrow=T),
           Wmat=my.Wmat,
           m0=t(matrix(c(5,0,25,0))), #initial state - currently
x,x*,y,y* (*=velocity)
           # initialize cov matrix for the filter
           C0=matrix(c(5,-0.5,0.5,0.5,-0.5,0.5,0,0,0.5,0,5,0,0.5,0,0,1),nrow=4,byrow=T)
           )
kfilter(kal.SS)
######################################################################
And the error it produces:
Error in y - f : non-conformable arrays

If I look at the offending variables, here's what I get, and obviously
it's impossible to add these two

Browse[1]> y
     [,1]
[1,]    5
[2,]    0
[3,]   25
[4,]    0
Browse[1]> f
     [,1]
[1,]    5
[2,]   25
######################################################################
Should I simply coerce the dimensions of my inputs such that the
dimension of my observation vectors are the same as the dimensions of
my state vectors?  Thank you in advance.

-John Dryden



More information about the R-help mailing list