[R] How to call to R_KalmanLike from outside StructTS

Javier López-de-Lacalle javlacalle at yahoo.es
Sat Sep 11 00:08:50 CEST 2010


Dear all:

I want to modify the 'StructTS' function from the 'stats' package. First, I am writing a working copy of the original version and got some problems.

I have two versions of the function plus the original one. The first version is the same code as the 'StructTS' function:

StructTS.v1 <- function (x, type = c("level", "trend", "BSM"), init = NULL, 
    fixed = NULL, optim.control = NULL) 
{
    KalmanLike2 <- function(y, mod, nit = 0) {
        x <- .Call(R_KalmanLike, y, mod$Z, mod$a, mod$P, mod$T, 
            mod$V, mod$h, mod$Pn, as.integer(nit), FALSE, fast = TRUE)
        0.5 * sum(x)/length(y)
    }
#...
#... above and remaining code is the same as the original code in StructTS
#...
}

Running this version gives the following error:

R> StructTS.v1(log(AirPassengers), type = "BSM")
Error in KalmanLike2(y, Z, -1) : object 'R_KalmanLike' not found

In the second version I modify the internal function 'KalmanLike2'
using the function 'KalmanLike' instead of calling 'R_KalmanLike'.

StructTS.v2 <- function (x, type = c("level", "trend", "BSM"), init = NULL, 
    fixed = NULL, optim.control = NULL) 
{
    KalmanLike2 <- function(y, mod, nit = 0) {
      KalmanLike(y = y, mod = mod, nit = as.integer(nit), fast = TRUE)$Lik 
    }
    makeLevel <- function(x) {
        T <- matrix(1, 1L, 1L)
#...
#... remaining code is the same as the original code in StructTS
#...
}

With this version the previous error is avoided but it yields results different from the original version. The fitted components are similar but the parameter estimates are different, so something is wrong with the second version.

R> v0 <- StructTS(log(AirPassengers), type = "BSM")
R> v2 <- StructTS.v2(log(AirPassengers), type = "BSM")
R> identical(v0$coef, v2$coef)
[1] FALSE

As I want to try some changes in the original function, I need a working copy of it. That is, I don't want just renaming the function like this:

R> StructTS.v1 <- StructTS  # this is not the idea

How can I call to 'R_KalmanLike', should I load something via dyn.load()?

Thanks

javi







More information about the R-help mailing list