
Modeling 07: Spatial and Space-Time Bayesian Models
climasus4r Team
17/10/2026
Source:vignettes/mod-07-bayes.Rmd
mod-07-bayes.RmdObjective
By the end of this tutorial you will be able to:
- Fit a cross-sectional BYM (Besag-York-Mollié) model
with
sus_mod_spatial_bayes()to obtain smoothed relative risks by municipality; - Visualize the relative risk map, the
uncertainty map, and the fixed-effects forest
plot with
sus_mod_plot_spatial_bayes(); - Build and fit a hierarchical space-time model (BYM2
+ RW2 + Knorr-Held type I interaction) with
sus_mod_spacetime_bayes(); - Explore the space-time decomposition — structured spatial effect,
temporal trend, and interaction — with
sus_mod_plot_spacetime(); - Compute exceedance probabilities
for different risk thresholds with
sus_mod_spacetime_exceedance(); - Generate approximate forecasts for future periods
by extrapolating the linear predictor via
sus_mod_spacetime_predict().
This tutorial covers the Bayesian modeling stage of the climasus4r pipeline — which follows the classical spatial models (Tutorial 06) and precedes the vulnerability and SWOT analysis (Tutorial 08).
Scientific context
Why Bayesian models in spatial epidemiology?
Small-area epidemiology — where the outcome is counted in municipalities, census tracts, or administrative regions — faces three structural challenges that classical models do not adequately solve:
- Instability of estimates in small-population areas: municipalities with few inhabitants show extremely variable crude rates, not because the risk is truly high but because of random fluctuation (Lawson, 2018).
- Spatial dependence: neighboring municipalities share environmental exposures, socioeconomic patterns, and access to services. Ignoring this structure produces correlated residuals and misleading inference (Besag, York & Mollié, 1991).
- Temporal dimension: in multi-year studies, risk evolves smoothly over time. Explicitly modeling this evolution yields more precise estimates and allows detection of trends and seasonality (Knorr-Held, 2000).
Hierarchical Bayesian models solve the first problem via smoothing by borrowing strength: small-population municipalities have their risk estimated partly from the prior distribution and from their neighbors. The second is addressed by random effects with CAR structure (Conditional Autoregressive). The third, by random-walk processes over time.
The BYM model
The Besag, York and Mollié (1991) model — BYM — decomposes the risk of each area as:
where:
- is the intercept (mean log-risk level);
- is the contribution of the fixed effects (climatic and environmental covariates);
- is the spatially structured random effect — it follows an intrinsic CAR distribution (ICAR), which ensures that neighboring areas have similar values;
- is the unstructured random effect — it captures residual heterogeneity independent of geographic position.
The expected outcome rate in area is , where is the expected count (offset).
The BYM2 model (Riebler et al., 2016)
The BYM2 model reparametrizes the original BYM with a single precision parameter and a mixing parameter :
where is the scaled ICAR component and . The parameter quantifies the proportion of variance attributable to spatial structure. Penalized complexity (PC) priors are used: and .
The Knorr-Held (2000) space-time model
For panel data (area time), the linear predictor becomes:
where:
- is the spatial random effect (BYM2);
- is the structured temporal effect (second-order random walk, RW2);
- is the space-time interaction (type I: IID; type IV: structured in both dimensions);
- is the expected count (offset).
Knorr-Held (2000) proposes four interaction types: IID (type I), structured in time (type II), structured in space (type III), and structured in both dimensions (type IV).
Bayesian exceedance
The exceedance probability is the posterior probability that the relative risk in area exceeds a threshold :
This is a fundamental tool for epidemiological surveillance: rather than reporting just the mean RR — which may be high but uncertain — it translates posterior uncertainty into a probabilistic decision. When posterior samples are not directly available, the lognormal approximation of Richardson et al. (2004) is used:
where is the estimated standard deviation of the log-RR derived from the 95% credible interval (Richardson et al., 2004).
Data used
| Object | Origin | Role |
|---|---|---|
caso_espacial.rds |
Previous pipeline (Tutorial 06) | SF of RMSP municipalities with code_muni,
n_obitos, pop, temp_med
|
mod_weights.rds |
Tutorial 06 |
climasus_weights object (RMSP Queen weights) |
caso_serie.rds |
Tutorial 05 (optional) | Daily death series — grouped by municipality × year |
Driving case: temperature and respiratory mortality in older adults (J00–J99) in the São Paulo metropolitan region, 2014–2019, 39 municipalities.
Complete pipeline
Load package and data
library(climasus4r)
# Carregar sf de municípios (caso_espacial.rds) e pesos (mod_weights.rds)
rmsp_sf <- readRDS("vignettes-pt/dados/caso_espacial.rds")
mod_weights <- readRDS("vignettes-pt/dados/mod_weights.rds")
# Dados tabulares sem geometria para sus_mod_spatial_bayes
df_cross <- sf::st_drop_geometry(rmsp_sf)Cross-sectional BYM model
fit_bym <- sus_mod_spatial_bayes(
df = df_cross,
outcome = "n_obitos", # coluna de contagens
W = mod_weights, # climasus_weights (Tutorial 06)
covariates = "temp_med", # temperatura média como covariável fixa
offset = "expected", # contagens esperadas (log-offset)
family = "poisson",
model = "bym", # BYM via CARBayes/MCMC
n_iter = 10000L,
burnin = 2000L,
thin = 10L,
prior_tau2 = c(1, 0.01), # prior IG(1, 0.01) para tau^2 (fracamente informativo)
seed = 42L,
lang = "pt"
)
print(fit_bym)Visualizations of the BYM model
# Mapa de Risco Relativo suavizado
sus_mod_plot_spatial_bayes(
x = fit_bym,
municipalities = rmsp_sf,
type = "rr", # choropleth do RR posterior
lang = "pt"
)
# Mapa de incerteza (largura do IC95%)
sus_mod_plot_spatial_bayes(
x = fit_bym,
municipalities = rmsp_sf,
type = "uncertainty", # IC95% superior - IC95% inferior
lang = "pt"
)
# Forest plot de efeitos fixos
sus_mod_plot_spatial_bayes(
x = fit_bym,
type = "coef", # estimativas e IC95% dos betas
lang = "pt"
)
# Painel combinado RR + incerteza (requer patchwork)
sus_mod_plot_spatial_bayes(
x = fit_bym,
municipalities = rmsp_sf,
type = "both",
lang = "pt"
)Build the space-time panel (municipality × year)
# Agregar série diária por código de município e ano
painel_st <- readRDS("vignettes-pt/dados/caso_serie.rds") |>
dplyr::mutate(ano = as.integer(format(as.Date(date), "%Y"))) |>
dplyr::group_by(code_muni, ano) |>
dplyr::summarise(
n_obitos = sum(n_obitos, na.rm = TRUE),
.groups = "drop"
) |>
dplyr::left_join(
sf::st_drop_geometry(rmsp_sf[, c("code_muni", "pop", "temp_med", "expected")]),
by = "code_muni"
)Space-time BYM2 + RW2 model (INLA)
# Requer o pacote INLA (não está no CRAN)
# install.packages("INLA",
# repos = c(INLA = "https://inla.r-inla-download.org/R/stable"))
fit_st <- sus_mod_spacetime_bayes(
df = painel_st,
outcome = "n_obitos",
W = mod_weights,
time_col = "ano", # coluna de tempo (inteiro ou Date)
time_unit = "year", # agregação anual
covariates = "temp_med", # efeito fixo: temperatura média
offset = "expected", # contagens esperadas (log-offset)
family = "poisson",
spatial_model = "bym2", # BYM2 com priores PC (Riebler et al. 2016)
temporal_model = "rw2", # passeio aleatório de 2ª ordem
interaction_type = "I", # interação IID (Knorr-Held tipo I)
pc_prior_u = 0.5, # P(sigma > 0.5) = 0.01
pc_prior_alpha = 0.01,
compute_waic = TRUE,
n_samples = 1000L,
seed = 42L,
lang = "pt"
)
print(fit_st)
# Salvar para reuso nos tutoriais seguintes
saveRDS(fit_st, "vignettes-pt/dados/mod_spacetime_fit.rds")Visualizations of the space-time model
# Tendência temporal do RR (média sobre municípios)
sus_mod_plot_spacetime(
x = fit_st,
type = "temporal", # linha com RR médio + IC95% ao longo do tempo
lang = "pt"
)
# Mapa coroplético de RR (média temporal por município)
sus_mod_plot_spacetime(
x = fit_st,
type = "rr_map", # choropleth do RR médio espaço-temporal
municipalities = rmsp_sf,
lang = "pt"
)
# Heatmap de interação espaço-tempo (município × período)
sus_mod_plot_spacetime(
x = fit_st,
type = "interaction", # gamma_{it}: efeito diferencial por célula
lang = "pt"
)
# Forest plot de efeitos fixos (modelo espaço-temporal)
sus_mod_plot_spacetime(
x = fit_st,
type = "coef",
lang = "pt"
)Exceedance probabilities
exc_resultado <- sus_mod_spacetime_exceedance(
fit = fit_st,
thresholds = c(1.0, 1.5, 2.0), # limiares de RR para P(RR > t)
lang = "pt",
verbose = TRUE
)
print(exc_resultado)
exc_resultado$n_exceed # contagem de células com P(RR > t) > 0.80
# Agregar excedências por ano (útil para vigilância)
exc_anual <- sus_mod_spacetime_exceedance(
fit = fit_st,
thresholds = c(1.0, 1.5, 2.0),
aggregate_time = "year", # média anual antes de calcular P(RR > t)
municipalities = rmsp_sf, # juntar geometria para mapeamento direto
lang = "pt"
)Approximate space-time forecast
# Previsão para 2 períodos à frente (horizonte = 2 anos)
pred_futuro <- sus_mod_spacetime_predict(
fit = fit_st,
newdata = NULL, # NULL => constrói grid automático
horizon = 2L, # 2 períodos além do último observado
include_ci = TRUE, # IC95% via propagação de variância
lang = "pt"
)
print(pred_futuro)
head(pred_futuro$predictions)
# Cenário contrafactual: +2 °C de temperatura
pred_counter <- sus_mod_spacetime_predict(
fit = fit_st,
newdata = painel_st, # grade observada
covariates_new = list(temp_med = painel_st$temp_med + 2), # override
include_ci = TRUE,
lang = "pt"
)Function characteristics
sus_mod_spatial_bayes() — Cross-Sectional Spatial
Bayesian Model
Fits a hierarchical Bayesian model for disease mapping across municipalities (or other areal units), using CAR priors via CARBayes (MCMC) or INLA (nested Laplace approximation).
Signature:
sus_mod_spatial_bayes(
df, outcome, W,
covariates = NULL,
offset = NULL,
family = c("poisson", "binomial", "gaussian"),
model = c("bym", "leroux", "independent", "bym2"),
n_iter = 10000L,
burnin = 2000L,
thin = 10L,
prior_tau2 = c(1, 0.01),
seed = 42L,
lang = "pt",
verbose = TRUE
)model parameter:
| Value | Engine | Description |
|---|---|---|
"bym" (default) |
CARBayes/MCMC | Besag-York-Mollié: ICAR + IID |
"leroux" |
CARBayes/MCMC | CAR with mixing parameter |
"independent" |
CARBayes/MCMC | IID random effects (no spatial structure) |
"bym2" |
INLA (requires separate installation) | Reparametrized BYM2 with PC priors |
Returns: an object of class
climasus_spatial_bayes with slots: - $fixed:
fixed effects (posterior mean, SD, 95% CI) - $random:
random effects by municipality (phi_mean,
phi_sd) - $rr: relative risk by municipality
(rr_mean, rr_lower95, rr_upper95)
- $fitted: fitted values (response scale) -
$dic: DIC (or a vector with DIC and WAIC for BYM2) -
$model, $family,
$n_iter_effective, $call
sus_mod_plot_spatial_bayes() — Spatial Bayesian Model
Visualizations
Produces maps and plots from a climasus_spatial_bayes
object.
Signature:
sus_mod_plot_spatial_bayes(
x,
municipalities = NULL,
type = c("rr", "uncertainty", "coef", "both"),
title = NULL,
base_size = 12,
lang = "pt",
...
)type parameter:
| Value | Description | Requires municipalities
|
|---|---|---|
"rr" (default) |
Choropleth of the mean posterior RR; municipalities whose 95% CI lies entirely above 1 get a black border | Yes |
"uncertainty" |
Choropleth of 95% CI width (plasma palette) | Yes |
"coef" |
Forest plot of fixed effects with 95% CI | No |
"both" |
Side-by-side RR + uncertainty panel (uses patchwork if
available) |
Yes |
Returns: a ggplot object (or
patchwork for "both").
sus_mod_spacetime_bayes() — Space-Time Bayesian Model
(INLA)
Fits a full hierarchical space-time model using INLA. Requires the INLA package (not on CRAN; see installation instructions below).
Signature:
sus_mod_spacetime_bayes(
df,
outcome,
W,
time_col = "date",
time_unit = c("year", "month", "week", "auto"),
covariates = NULL,
offset = NULL,
family = c("poisson", "nbinomial", "binomial", "gaussian"),
spatial_model = c("bym2", "bym", "besag", "iid"),
temporal_model = c("rw1", "rw2", "ar1", "iid_time"),
interaction_type = c("none", "I", "II", "III", "IV"),
pc_prior_u = 0.5,
pc_prior_alpha = 0.01,
compute_waic = TRUE,
compute_cpo = FALSE,
exceedance_threshold = 1.0,
n_samples = 1000L,
seed = 42L,
lang = "pt",
verbose = TRUE
)Main parameters:
| Parameter | Possible values | Role |
|---|---|---|
spatial_model |
"bym2" (default), "bym",
"besag", "iid"
|
Structure of the spatial effect |
temporal_model |
"rw1", "rw2" (default),
"ar1", "iid_time"
|
Structure of the temporal effect |
interaction_type |
"none", "I" through "IV"
|
Knorr-Held (2000) interaction type |
time_unit |
"year", "month", "week",
"auto"
|
Temporal granularity |
Returns: an object of class
climasus_spacetime_bayes with slots: - $fixed:
fixed effects (mean, sd, lower95, upper95, mode) - $rr: RR
by cell (code_muni × time_idx) with p_exceed -
$spatial_re: spatial effect by municipality
(phi_mean, phi_sd) -
$temporal_re: temporal effect by period
(psi_mean, psi_sd) -
$interaction_re: interaction by cell
(gamma_mean, gamma_sd) or NULL -
$waic, $dic: fit criteria -
$model_spec, $call, $n_areas,
$n_times
sus_mod_plot_spacetime() — Space-Time Model
Visualizations
Produces five plot types from climasus_spacetime_bayes
or climasus_spacetime_exceedance objects.
Signature:
sus_mod_plot_spacetime(
x,
type = c("rr_map", "temporal", "interaction", "exceedance", "coef"),
municipalities = NULL,
threshold = 1.0,
lang = "pt",
...
)type parameter:
| Value | Description | Requires municipalities
|
Requires climasus_spacetime_exceedance
|
|---|---|---|---|
"rr_map" |
Choropleth of the mean RR (averaged over periods, or per period via
time_idx) |
Yes | No |
"temporal" |
Time series of the mean RR across municipalities + 95% CI | No | No |
"interaction" |
Heatmap (municipality × period) | No | No |
"exceedance" |
Choropleth of | Yes | Yes (climasus_spacetime_exceedance) |
"coef" |
Forest plot of fixed effects | No | No |
sus_mod_spacetime_exceedance() — Exceedance
Probabilities
Computes for each municipality × period cell.
Signature:
sus_mod_spacetime_exceedance(
fit,
thresholds = c(1.0, 1.5, 2.0),
aggregate_time = NULL,
municipalities = NULL,
lang = "pt",
verbose = TRUE
)Main parameters:
| Parameter | Role |
|---|---|
thresholds |
Vector of thresholds
for
;
generates columns p_gt_1_0, p_gt_1_5,
etc. |
aggregate_time |
"year" or "month" to aggregate temporally
before computation; NULL = no aggregation |
municipalities |
sf object for direct spatial join of the result |
Returns: an object of class
climasus_spacetime_exceedance with: -
$exceedance: data.frame with code_muni,
time_idx (or time_period),
rr_mean, p_gt_* columns -
$thresholds: vector of thresholds used -
$n_exceed: data.frame with a count of cells where
sus_mod_spacetime_predict() — Approximate Space-Time
Forecast
Generates approximate forecasts via the linear predictor for future periods or counterfactual scenarios.
Signature:
sus_mod_spacetime_predict(
fit,
newdata = NULL,
horizon = 0L,
covariates_new = NULL,
include_ci = TRUE,
return_samples = FALSE,
lang = "pt",
verbose = TRUE
)Main parameters:
| Parameter | Role |
|---|---|
horizon |
Periods ahead when newdata = NULL; extrapolation via
RW1/RW2 |
newdata |
Data.frame with code_muni + time_idx +
covariates, for in-sample forecasting or a counterfactual scenario |
covariates_new |
Named list of covariate overrides
(e.g. list(temp_med = temp + 2)) for scenario analysis |
include_ci |
If TRUE, computes 95% CI via propagation of posterior
variance |
Returns: an object of class
climasus_spacetime_pred with: - $predictions:
data.frame with code_muni, time_idx,
pred_mean, pred_lower95,
pred_upper95 - $n_predicted,
$horizon, $call
Important note: this function uses an approximate linear predictor. For exact posterior predictive distributions, refit
sus_mod_spacetime_bayes()with the complete dataset including the future periods.
Illustrated results
Figure 1 — BYM Relative Risk Map (cross-sectional)

Figure 1. Choropleth map of the relative risk smoothed by the BYM (Besag-York-Mollié) model. Diverging scale centered on RR = 1.0 (navy blue = below-average risk; red = above average). Municipalities whose 95% CI lies entirely above 1 have a black border (significantly elevated risk). Source: climasus4r / sus_mod_spatial_bayes().
Figure 2 — Posterior Uncertainty (95% CI width)

Figure 2. Uncertainty map: width of the 95% credible interval for the relative risk by municipality. Municipalities with high uncertainty (dark plasma palette) generally have small populations or sparse data. Source: climasus4r / sus_mod_plot_spatial_bayes(type=‘uncertainty’).
Figure 3 — Forest Plot of Fixed Coefficients (BYM)

Figure 3. Forest plot of the fixed effects of the BYM model: posterior mean (point) and 95% credible interval (horizontal line). The vertical dashed line at zero is the reference for no effect. Source: climasus4r / sus_mod_plot_spatial_bayes(type=‘coef’).
| term | mean | sd | lower95 | upper95 |
|---|---|---|---|---|
| temp_med | 0.1300 | NA | 0.0552 | 0.1842 |
| sigma2 | 0.2153 | NA | 0.0089 | 0.5085 |
Figure 4 — Temporal Trend of RR (Space-Time Model)

Figure 4. Temporal trend of the mean relative risk (across all RMSP municipalities), with 95% credible interval. The temporal effect is estimated by a second-order random walk (RW2), capturing smooth acceleration and deceleration of the trend. Source: climasus4r / sus_mod_plot_spacetime(type=‘temporal’).
Figure 5 — Space-Time RR Map (Period Average)

Figure 5. Choropleth map of the mean relative risk across the whole study period (2014-2019), estimated by the BYM2 + RW2 space-time model. Bayesian smoothing is twofold: spatial (BYM2) and temporal (RW2). Source: climasus4r / sus_mod_plot_spacetime(type=‘rr_map’).
Figure 6 — Exceedance Probability

Figure 6. Map of the posterior exceedance probability P(RR > 1.5), temporally averaged by municipality. Values near 1 indicate high certainty of risk more than 50% above expected. The lognormal approximation is used when only the posterior mean and 95% CI are available (Richardson et al., 2004). Source: climasus4r / sus_mod_spacetime_exceedance().
| threshold | n_cells_exceed |
|---|---|
| 1.0 | 234 |
| 1.5 | 234 |
| 2.0 | 234 |
Figure 7 — Approximate Forecast (Horizon = 2 Periods)

Figure 7. Forecast of the mean count of respiratory deaths for the two periods following the study period, using sus_mod_spacetime_predict(horizon = 2). Orange points: forecast periods; green band: 95% CI via variance propagation. Warning: approximate linear predictor — for exact predictive distributions, refit the model with the complete data. Source: climasus4r / sus_mod_spacetime_predict().
Implementation notes and best practices
Installing INLA
The INLA package is not on CRAN. To install it:
install.packages(
"INLA",
repos = c(INLA = "https://inla.r-inla-download.org/R/stable",
getOption("repos"))
)Guarding calls to Suggests packages
Any call to INLA, CARBayes, spdep, or sf must be guarded:
if (!requireNamespace("INLA", quietly = TRUE)) {
stop("INLA necessário: instale com install.packages('INLA', ...)")
}Choosing the spatial model
| Situation | Recommended model |
|---|---|
| Fast exploratory analysis, no INLA |
model = "bym" (CARBayes) |
| Well-calibrated priors, scalability |
model = "bym2" (INLA) |
| Suspected weak dependence | model = "leroux" |
| Unstructured heterogeneity only | model = "independent" |
Choosing the temporal model
| Situation | Recommended model |
|---|---|
| Smooth trend (recommended for health) | temporal_model = "rw2" |
| More local, year-to-year trend | temporal_model = "rw1" |
| Short-term autocorrelation | temporal_model = "ar1" |
References
Anselin, L. (1988). Spatial Econometrics: Methods and Models. Kluwer Academic Publishers.
Besag, J., York, J., & Mollié, A. (1991). Bayesian image restoration, with two applications in spatial statistics. Annals of the Institute of Statistical Mathematics, 43(1), 1–20.
Blangiardo, M., & Cameletti, M. (2015). Spatial and Spatio-temporal Bayesian Models with R-INLA. Wiley.
Gelman, A., Carlin, J. B., Stern, H. S., Dunson, D. B., Vehtari, A., & Rubin, D. B. (2013). Bayesian Data Analysis (3rd ed.). CRC Press.
Held, L., & Schrödle, B. (2010). Posterior and cross-validatory predictive checks: a comparison of MCMC and INLA. In Statistical Modelling and Regression Structures (pp. 91–110). Physica-Verlag.
Knorr-Held, L. (2000). Bayesian modelling of inseparable space-time variation in disease risk. Statistics in Medicine, 19(17–18), 2555–2567.
Lawson, A. B. (2018). Bayesian Disease Mapping: Hierarchical Modeling in Spatial Epidemiology (3rd ed.). CRC Press.
Lee, D. (2013). CARBayes: an R package for Bayesian spatial modelling with conditional autoregressive priors. Journal of Statistical Software, 55(13), 1–24.
Leroux, B. G., Lei, X., & Breslow, N. (2000). Estimation of disease rates in small areas: a new mixed model for spatial dependence. In Statistical Models in Epidemiology, the Environment, and Clinical Trials (pp. 179–191). Springer.
Richardson, S., Thomson, A., Best, N., & Elliott, P. (2004). Interpreting posterior relative risk estimates in disease-mapping studies. Environmental Health Perspectives, 112(9), 1016–1025.
Riebler, A., Sørbye, S. H., Simpson, D., & Rue, H. (2016). An intuitive Bayesian spatial model for disease mapping that accounts for scaling. Statistical Methods in Medical Research, 25(4), 1145–1165.
Rue, H., Martino, S., & Chopin, N. (2009). Approximate Bayesian inference for latent Gaussian models by using integrated nested Laplace approximations. Journal of the Royal Statistical Society: Series B, 71(2), 319–392.
Navigation
| Previous | This page | Next |
|---|---|---|
| Spatial Models | Bayesian Models | Vulnerability and SWOT |