I am trying to create SSModel
from KFAS
package in R. In the code I got from someone it was done this way:
model <- KFAS::SSModel(ts ~ -1 + SSMcustom(Z = Z_t,T = T_t, R = R_t, Q = Q_t, a1 = a1_t, P1 = P1_t))
and worked correctly. In order to make code more readable I decided to instead of creating SSMcustom
inside the SSModel
call (which results in too long formula that needs to be splitted in two lines of code), do this:
ssm <- SSMcustom(Z = Z_t,T = T_t, R = R_t, Q = Q_t, a1 = a1_t, P1 = P1_t) # creates an object
model <- KFAS::SSModel(ts ~ -1 + ssm) # error
and I got this error: Error in model.frame.default(formula = ts ~ -1 + ssm, na.action = na.pass) : invalid type (list) for variable 'ssm'
.
Why? I want to understand this behaviour just to understand R better.
MRE
library(KFAS)
# Create time series
data <- 1:100
ts <- ts(data, start=c(2023, 10), frequency=12)
# Define state space parameters
lambda <- 1600
Z_t <- matrix(c(1, 0), nrow = 1, ncol = 2)
T_t <- matrix(c(2, 1, -1, 0), nrow = 2, ncol = 2)
R_t <- matrix(c(1, 0, 0, 1), nrow = 2, ncol = 2)
Q_t <- matrix(c(1/lambda, 0, 0, 0), nrow = 2, ncol = 2)
a1_t <- matrix(c(0, 0), nrow = 2, ncol = 1)
P1_t <- matrix(c(1e+07, 0, 0, 1e+07), nrow = 2, ncol = 2)
model_good <- KFAS::SSModel(ts ~ -1 + SSMcustom(Z = Z_t, T = T_t, R = R_t, Q = Q_t, a1 = a1_t, P1 = P1_t))
model_good
ssm <- SSMcustom(Z = Z_t, T = T_t, R = R_t, Q = Q_t, a1 = a1_t, P1 = P1_t)
model_error <- KFAS::SSModel(ts ~ -1 + ssm)