Skip to content

Instantly share code, notes, and snippets.

@ito4303
Created August 29, 2018 20:12
Show Gist options
  • Save ito4303/67294c57f46413ac842ec5a6bde7e57e to your computer and use it in GitHub Desktop.
Save ito4303/67294c57f46413ac842ec5a6bde7e57e to your computer and use it in GitHub Desktop.
KFAS model with offset
# KFAS model with offset
set.seed(20180830)
T <- 100
sigma <- 0.05
dens <- rep(NA, T)
dens[1] <- 0.5
for (t in 2:T)
dens[t] <- exp(rnorm(1, log(dens[t - 1]), sigma))
area <- rep(c(10, 20), T / 2)
y <- rpois(T, dens * area)
# plot(1:T, dens, type = "l")
# plot(1:T, y, type = "l")
library(KFAS)
model <- SSModel(y ~ SSMtrend(1, Q = NA), u = area, distribution = "poisson")
fit <- fitSSM(model, inits = c(0), method = "Brent", lower = -100, upper = 100)
out <- KFS(fit$model, filtering = "state")
plot(1:T, y, type = "l")
lines(1:T, out$muhat, col = "red")
plot(1:T, dens, type = "l")
lines(1:T, exp(out$alphahat), col = "red")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment