I tried to model the interaction between time and space, but I ran into a problem.
Opened this issue · 1 comments
Hello, I am using INLA package, I already have 10 regions and 18 years of data, and then I want to try the interaction of time and space, so I wrote the following code, but will encounter errors, can you ask how to solve, thank you.
library(inla)
n_regions <- 10
n_years <- 18
region_id <- rep(1:n_regions, each = n_years)
year <- rep(1:n_years, times = n_regions)
true_spatial_effect <- rnorm(n_regions, 0, 2)
true_time_effect <- rnorm(n_years, 0, 2)
interaction_effect <- outer(true_spatial_effect, true_time_effect)
true_mean <- true_spatial_effect[region_id] + true_time_effect[year] + interaction_effect[region_id, year]
infection_count <- rnorm(n_regions * n_years, mean = true_mean, sd = 3)
data <- data.frame(region = region_id, year = year, infection = infection_count)
formula <- infection ~ -1 + f(region, model = "bym", graph = ~region,
hyper = list(prec.unstruct = list(prior="loggamma", param=c(1,0.01)),
prec.spatial = list(prior="loggamma", param=c(1,0.01)))) +
f(year, model = "ar1", hyper = list(prec = list(prior = "loggamma", param = c(1, 0.01)))) +
f(region:year, model = "iid", hyper = list(prec = list(prior = "loggamma", param = c(1, 0.01))))
result <- inla(formula, family = "gaussian", data = data)
The error is as follows. Since my region is a string, do I need to replace it with 1:10, and the time is from 2005 to 2022, I use 1:10 here to represent 10 regions and 1:18 to represent 18 years. I'm trying to express interaction effects as unique=n_regions * n_years. Is this a good idea, and if not, how to design the code? Thank you. How about if you don't have time, don't hurry back to me, I'll read the literature again, thank you again.
result <- inla(formula, family = "gaussian", data = data)
*** inla.core.safe: The inla program failed, but will rerun in case better initial values may help. try=1/1
error inla.core.safe(formula = formula, family = family, contrasts = contrasts, :
SOMETHING STRANGE: You probably used one variable as a covariate more than once.
The inla program failed and the maximum number of tries has been reached.
Run rlang::last_trace()
to see where the error occurred.
You can't use the "a:b" special notation as input to f()
. The normal approach to covariance-separable space-time interaction is to use space as the main variable, and time as either replicate
(for temporal independence) or group
(for a sub-set of dependence models), In your example case, I think +f(region, model = ..., replicate = year)
is the one you're looking for. Alternatively, but only useful in the iid special case, is to precompute a joint "region and year" index; region_year = seq_len(n_regions * n_years)
and use +f(region_year, model = "iid", ...)