suppressPackageStartupMessages({
library(INLA)
library(fmesher)
})
set.seed(42)
# Simulate a small lagged exposure data set.
n <- 100L
lags <- 1:3
x_full <- as.numeric(arima.sim(list(ar = 0.6), n = n + max(lags), sd = 0.5))
Xlag <- sapply(0:max(lags), \(l) x_full[(max(lags) + 1L - l):(n + max(lags) - l)])
colnames(Xlag) <- paste0("lag", 0:max(lags))
dat <- data.frame(
y = rpois(n, exp(0.3 + 0.4 * Xlag[, "lag1"] - 0.2 * Xlag[, "lag2"])),
t = seq_len(n),
x = Xlag[, "lag0"],
group_dummy = 1L
)
lag_x <- function(t, lag) Xlag[t, paste0("lag", lag)]
mesh <- fm_mesh_1d(
seq(min(Xlag), max(Xlag), length.out = 12),
degree = 2,
boundary = "free"
)
spde <- inla.spde2.pcmatern(
mesh,
prior.range = c(1, 0.01),
prior.sigma = c(1, 0.01)
)
A_lag <- Reduce(
`+`,
lapply(lags, \(lag) {
inla.spde.make.A(
mesh = mesh,
loc = matrix(lag_x(dat$t, lag), ncol = 1),
group = rep(lag, n),
n.group = length(lags)
)
})
)
# Plain INLA with global stack A matrix.
idx <- inla.spde.make.index(
name = "LagEffect",
n.spde = spde$n.spde,
n.group = length(lags)
)
stk <- inla.stack(
data = list(y = dat$y),
A = list(1, A_lag),
effects = list(
data.frame(Intercept = rep(1, n)),
idx
)
)
fit_stack <- inla(
y ~ 0 + Intercept +
f(
LagEffect,
model = spde,
group = LagEffect.group,
control.group = list(model = "ar1")
),
family = "poisson",
data = inla.stack.data(stk),
control.predictor = list(
A = inla.stack.A(stk),
compute = TRUE
),
control.fixed = list(mean = 0, prec = 0.01),
control.compute = list(config = TRUE),
verbose = F
)
# Plain INLA with local A matrix on the f() term.
fit_alocal <- inla(
y ~ 0 + Intercept +
f(
LagEffect,
w0,
model = spde,
group = LagEffect.group,
ngroup = length(lags),
control.group = list(model = "ar1"),
A.local = A_lag,
values = seq_len(spde$n.spde)
),
family = "poisson",
data = list(
y = dat$y,
Intercept = rep(1, n),
LagEffect = rep(seq_len(spde$n.spde), length.out = n),
LagEffect.group = rep(lags, length.out = n),
w0 = rep(0, n),
A_lag = A_lag
),
control.fixed = list(mean = 0, prec = 0.01),
control.compute = list(config = TRUE),
verbose = F
)
fit_stack <- inla.rerun(fit_stack)
fit_alocal <- inla.rerun(fit_alocal)