| Title: | Bayesian Hierarchical Modelling of Spatio-Temporal Health Data |
| Version: | 0.2.0 |
| Description: | Supports modeling health outcomes using Bayesian hierarchical spatio-temporal models with complex covariate effects (e.g., linear, non-linear, interactions, distributed lag linear and non-linear models) in the 'INLA' framework. It is designed to help users identify key drivers and predictors of disease risk by enabling streamlined model exploration, comparison, and visualization of complex covariate effects. See an application of the modelling framework in Lowe, Lee, O'Reilly et al. (2021) <doi:10.1016/S2542-5196(20)30292-8>. |
| License: | GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] |
| URL: | https://gitlab.earth.bsc.es/ghr/ghrmodel, https://bsc-es.github.io/GHRtools/docs/GHRmodel/GHRmodel |
| BugReports: | https://gitlab.earth.bsc.es/ghr/ghrmodel/-/work_items |
| Depends: | R (≥ 4.1.0) |
| Imports: | cowplot, dlnm, dplyr, ggplot2 (≥ 3.5.0), GHRexplore (≥ 0.3.0), rlang, scales, tidyr, tidyselect, zoo, stringr, VGAM |
| Suggests: | INLA, sf, sn, RColorBrewer, colorspace, testthat (≥ 3.0.0), spdep, knitr, rmarkdown |
| Additional_repositories: | https://inla.r-inla-download.org/R/stable |
| Config/testthat/edition: | 3 |
| Encoding: | UTF-8 |
| LazyData: | true |
| VignetteBuilder: | knitr |
| Config/roxygen2/version: | 8.1.1 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-17 14:38:22 UTC; cmilagar |
| Author: | Giovenale Moirano |
| Maintainer: | Carles Milà <carles.milagarcia@bsc.es> |
| Repository: | CRAN |
| Date/Publication: | 2026-11-18 10:10:21 UTC |
GHRmodel: Bayesian Hierarchical Modelling of Spatio-Temporal Health Data
Description
Supports modeling health outcomes using Bayesian hierarchical spatio-temporal models with complex covariate effects (e.g., linear, non-linear, interactions, distributed lag linear and non-linear models) in the 'INLA' framework. It is designed to help users identify key drivers and predictors of disease risk by enabling streamlined model exploration, comparison, and visualization of complex covariate effects. See an application of the modelling framework in Lowe, Lee, O'Reilly et al. (2021) doi:10.1016/S2542-5196(20)30292-8.
Author(s)
Maintainer: Carles Milà carles.milagarcia@bsc.es (ORCID)
Authors:
Carles Milà carles.milagarcia@bsc.es (ORCID)
Giovenale Moirano (ORCID)
Anna B. Kawiecki (ORCID)
Diego Villa (ORCID)
Rachel Lowe (ORCID)
See Also
Useful links:
Report bugs at https://gitlab.earth.bsc.es/ghr/ghrmodel/-/work_items
Convert R-INLA Model Formulas into a GHRformulas Object
Description
This function converts a character vector of suitable R-INLA formulas into a
structured GHRformulas object. The GHRformulas object contains the
standardized information about the fixed effects, the random effects, and the
outcome variable, ensuring consistency across multiple models to be fitted
using the fit_models function.
Usage
as_GHRformulas(formulas)
Arguments
formulas |
A character vector of model formulas formatted for R-INLA.
Each formula must contain a single |
Details
The as_GHRformulas() function parses each input formula to extract the
outcome variable, fixed effects (covariates), and random effects. The
resulting GHRformulas object is designed to be used with the
fit_models function for model fitting with R-INLA.
Value
A structured list of class GHRformulas with the components:
formulasA character vector identical to the input
formulas(unmodified, in the same order).varsA data frame where each row corresponds to a formula and each column to a covariate slot. Cells hold the covariate term present at that position for the given formula, or
NAif that formula has fewer terms than the row with the most.reA character vector of the random effects specified across all formulas (identical across formulas by construction, see Details).
character(0)if none are present; otherwise named"re_1","re_2", ... in the order they were found.outcomeA character string indicating the outcome variable (must be consistent across formulas).
See Also
write_inla_formulas to generate R-INLA compatible
input formulas.
Examples
# Define formulas
formulas <- c(
"dengue_cases ~ 1 + f(month_id, model = 'rw1')",
"dengue_cases ~ 1 + f(month_id, model = 'rw1') + tmin.l1")
# Convert the formulas into a GHRformulas object
formulas <- as_GHRformulas(formulas)
# Inspect the structured GHRformulas object
print(formulas)
# Visualize output: GHRformulas object
class(formulas)
Add Covariates to All Combinations
Description
This function appends one or more covariate names to all elements
(i.e., covariate sets) in a list of character vectors. This is
useful when a covariate (like a confounder or control variable)
needs to be included in every model. It also works with a single
character vector input. The resulting list can be input into the
covariates argument in write_inla_formulas.
Usage
cov_add(covariates, name, add = FALSE)
Arguments
covariates |
A character vector or a list of character vectors, where
each vector represents a set of covariates (e.g., from
|
name |
A character vector of covariate names to be added to each set. |
add |
Boolean that indicates if the original combinations in the
|
Value
A list of character vectors, with each vector containing the original
covariates plus the additional ones specified in the name argument.
Examples
# Multiple combinations
cov_sets <- list(
c("tmin", "pdsi"),
c("tmin.l1", "pdsi"),
c("tmin.l2", "pdsi")
)
cov_add(cov_sets, name = "urban")
Generate Interaction Terms Between Covariates
Description
This function generates interaction terms between covariates specified in
the pattern or name arguments. It requires a list of character vectors
and appends interaction terms to each vector based on pairwise or
three-way interactions. More-way interactions are not supported and will be
ignored. The resulting list can be input into the
covariates argument in write_inla_formulas.
Usage
cov_interact(covariates = NULL, pattern = NULL, name = NULL, add = FALSE)
Arguments
covariates |
A list of character vectors, each vector containing
variable names. Typically an output of |
pattern |
A character vector of length 2 or 3 specifying prefixes of variables to interact (e.g., "tmin" matches "tmin", "tmin.l1", etc.). |
name |
A character vector specifying the exact variable names to be included in the interactions. |
add |
Logical; if |
Details
If two variables are matched, their pairwise interaction is added (
var1:var2).If three variables are matched, two-way and three-way interactions are generated.
Only variables that are expressed as linear terms can be used in interactions.
Use either
pattern,name, or both to identify variables for interaction.
Value
A list of character vectors, where each vector includes covariates
and their corresponding interaction terms. This object can be passed to the
covariates argument in write_inla_formulas.
Examples
# Example dataset
data <- data.frame(tmin.l1 = rnorm(10), pdsi.l1 = rnorm(10),
urban = rnorm(10))
# Extract names
covs <- extract_names(data, pattern = c("tmin", "pdsi", "urban"))
# Create combinations
combos <- cov_multi(covariates = covs, pattern = c("tmin", "pdsi"))
# Add interaction terms
cov_interact(covariates = combos, pattern = c("tmin", "pdsi"))
# Output can be passed to write_inla_formulas()
new_covs <- cov_interact(combos, pattern = c("tmin", "pdsi"))
formulas <- write_inla_formulas(outcome = "cases", covariates = new_covs)
Create Covariate Combinations Across Groups
Description
This function generates all possible combinations of covariates by selecting
one variable from each user-defined group. Groups can be defined either by a
regular expression pattern (pattern) or by exact variable names (name).
The resulting list can be input into the covariates argument in
write_inla_formulas to generate multivariable model formulas
where all combinations of covariates are needed.
Usage
cov_multi(covariates, pattern = NULL, name = NULL, add = FALSE)
Arguments
covariates |
A character vector or a list of single-element character
vectors. Typically obtained from |
pattern |
A character vector of regular expression patterns (e.g., "tmin" matches "f(INLA::inla.group(tmin.l1, method='quantile', n=10), model='rw2')"). Each pattern defines a group to draw covariates from. |
name |
A character vector of exact variable names to include as an additional group. |
add |
Logical; if |
Value
A list of character vectors. Each element is a unique combination
of covariates, where one variable is drawn from each specified group. The
resulting list is suitable as input in the covariates argument in
write_inla_formulas.
Examples
data <- data.frame(tmin = rnorm(10), tmin.l1 = rnorm(10),
pdsi = rnorm(10), urban = rnorm(10))
# Extract covariate names
covs <- extract_names(data, pattern = c("tmin", "pdsi", "urban"))
# Combine "tmin" and "pdsi" into all possible pairings
cov_multi(covariates = covs, pattern = c("tmin", "pdsi"))
# Combine "tmin" and "urban", treating "urban" as an exact match
cov_multi(covariates = covs, pattern = "tmin", name = "urban")
# Use output as input to write_inla_formulas()
combined_covs <- cov_multi(covariates = covs, pattern = c("tmin", "pdsi"))
formulas <- write_inla_formulas(outcome = "cases",
covariates = combined_covs)
Create Non-Linear Effects for INLA
Description
This function transforms selected covariates identified by pattern or
name into non-linear terms using INLA's f() syntax. It supports random
walk models (rw1, rw2) and allows discretization by quantiles or equal
intervals. Transformed covariates are returned as character vectors inside
a list ready to be passed to the write_inla_formulas function.
Usage
cov_nl(
covariates,
pattern = NULL,
name = NULL,
model = "rw2",
method = "quantile",
n = 10,
replicate = NULL,
add = FALSE
)
Arguments
covariates |
A character vector or list of character vectors. Usually
from |
pattern |
Character vector of patterns to match covariates for transformation (e.g., "tmin" matches "tmin", "tmin.l1", etc.). |
name |
Character vector of exact covariate names to transform. |
model |
Character; either |
method |
Character; either |
n |
Integer; number of intervals or quantile bins. Must be >= 2. Default is 10. |
replicate |
Optional character string indicating a replicate structure for non-linear effects. |
add |
Logical; if |
Details
Use
patternorname(or both) to specify which variables to transform.The method and n arguments discretize the covariate into evenly populated bins.
The function supports discretization with either equal-width (
cut) or quantile-based (quantile) bins.The model argument imposes smoothness on the grouped effect, capturing non-linear trends.
Non-linear effects are created using
.single_non_linear_eff_inla()(internal helper).
Value
A list of character vectors. This object can be passed to the
covariates argument in write_inla_formulas.
See Also
See Bayesian inference with INLA: Smoothing for more information on smoothing and non-linear effects in R-INLA models.
Examples
data <- data.frame(tmin.l1 = rnorm(10), pdsi.l1 = rnorm(10))
covs <- extract_names(data, pattern = c("tmin", "pdsi"))
covlist <- cov_multi(covs, pattern = c("tmin", "pdsi"))
# Apply non-linear transformation to tmin variables
cov_nl(covlist, pattern = "tmin", model = "rw2")
# Include original variable along with transformed one
cov_nl(covlist, name = "pdsi.l1", model = "rw2", add = TRUE)
Build Univariable Covariate Sets
Description
This function returns a list where each element contains a single covariate,
based on covariates specified in the pattern or name arguments. This
structure is suitable for generating separate univariable model formulas
using write_inla_formulas.
Usage
cov_uni(covariates = NULL, pattern = NULL, name = NULL)
Arguments
covariates |
A character vector of covariate names. Typically the output
from |
pattern |
A character vector specifying the prefix pattern(s) to match (e.g., "tmin" matches "tmin", "tmin.l1", etc.). |
name |
A character vector specifying exact variable name(s) to extract. |
Value
A list of character vectors, each of length 1, containing the matched
covariate name. The resulting list is suitable for use as the covariates
argument in write_inla_formulas.
Examples
data <- data.frame(tmin = rnorm(10), tmin.l1 = rnorm(10), urban = rnorm(10))
covs <- extract_names(data, pattern = "tmin", name = "urban")
cov_uni(covs, pattern = "tmin")
cov_uni(covs, name = "urban")
Create Spatially or Temporally Varying Effects for INLA
Description
This function transforms covariates identified by pattern or name into
varying effect terms of the form:
f(unit, covariate, model = 'iid', constr = FALSE),
which allows covariates to have varying slopes across spatial or temporal
units. The output can be used directly in the covariates argument of
write_inla_formulas.
Usage
cov_varying(
covariates,
unit,
pattern = NULL,
name = NULL,
model = "iid",
constr = FALSE,
add = FALSE
)
Arguments
covariates |
A character vector or a list of character vectors of
covariate names. Typically output from |
unit |
Character string specifying the unit of variation (e.g.,
|
pattern |
A character vector specifying the prefix pattern(s) to match (e.g., "tmin" matches "tmin", "tmin.l1", etc.) for transformation. |
name |
Character vector of exact variable names to be transformed. |
model |
Character string specifying the INLA model for the varying
effect. Currently, only |
constr |
Logical. If TRUE it will impose a sum-to-zero constraint to the random effect. Default is FALSE. |
add |
Logical; if |
Details
Use
patternorname(or both) to specify which covariates to transform.Currently only supports
"iid"models for varying effects.
Value
A list of character vectors, each including covariates with varying
effects. The output is suitable as input for
write_inla_formulas.
Examples
data <- data.frame(tmin.l1 = rnorm(10), pdsi.l1 = rnorm(10))
covs <- extract_names(data, pattern = c("tmin", "pdsi"))
covlist <- cov_multi(covs, pattern = c("tmin", "pdsi"))
# Apply varying effect to tmin
cov_varying(covlist, pattern = "tmin", unit = "spat_id")
# Keep original and add varying effect terms
cov_varying(covlist, pattern = "tmin", unit = "spat_id", add = TRUE)
Create a Two-Dimensional INLA-compatible Cross-basis Matrix
Description
This function is a wrapper around dlnm::crossbasis
to generate cross-basis matrices that
capture nonlinear effects of a predictor across both exposure and lag
dimensions. The input covariate is passed as a numeric matrix of
lagged values, and the resulting columns can be renamed via
basis_name for easier reference in model formulas.
Usage
crossbasis_inla(covariate, basis_name, lag, argvar, arglag, ...)
Arguments
covariate |
A numeric matrix of covariate values. Typically this will
be a matrix of lagged covariate values (which can be generated using
|
basis_name |
A character string specifying the prefix for the spline
columns in the resulting basis matrix (replacing the default |
lag |
A numeric vector with min and max lag of the matrix (as in
|
argvar |
A list specifying the shape of the exposure-response function
with named elements (e.g., "fun", "df", "degree", "knots") as in
|
arglag |
A list specifying the shape of the lag-response function
with named elements (e.g., "fun", "df", "degree", "knots") as in
|
... |
Additional arguments passed to dlnm::crossbasis. |
Value
An object of class "crossbasis_inla" (also inheriting class
"crossbasis"), as returned by dlnm::crossbasis
but with column names prefixed by basis_name instead of the default
"v" (e.g. "v1.l1" becomes "basis_name1.l1").
See Also
onebasis_inla for the one-dimensional equivalent,
and crosspred_inla to compute predictions from a fitted
cross-basis.
Examples
# Build cross-basis with a custom prefix for columns
# Import example data set
data("dengue_MS")
lag_mat <- lag_cov(
data = dengue_MS,
name = c("tmin"),
time = "date",
lag = c(1:6),
group = "micro_code",
add = FALSE
)
cb_inla <- crossbasis_inla(
covariate = lag_mat,
basis_name = "tempLag",
lag = c(1, 6),
argvar = list(fun = "bs", df = 3),
arglag = list(fun = "poly", degree = 2)
)
# Check class of the cross-basis object
class(cb_inla)
# View resulting cross-basis matrix
head(colnames(cb_inla))
Generate DLNM Predictions from GHRmodels Objects
Description
This function takes an object of class GHRmodels, extracts the
relevant coefficients and variance-covariance matrix, and then calls
dlnm::crosspred to compute predictions over a range
of covariate values (or at specified points).
Usage
crosspred_inla(
models,
basis,
mod_id,
at = NULL,
from = NULL,
to = NULL,
by = NULL,
lag,
bylag = 1,
cen = NULL,
ci.level = 0.95,
cumul = FALSE
)
Arguments
models |
An object of class |
basis |
A cross-basis or one-basis object created by
|
mod_id |
An integer or character string specifying which model within
the input |
at |
A numeric vector of values at which to compute predictions (e.g.,
|
from, to |
Numeric values specifying the range of the prediction sequence
if |
by |
Numeric increment for the sequence if |
lag |
An optional vector of two elements with min and max lag. If
missing (default), it uses the same lag structure as defined in
|
bylag |
Numeric increment for lag steps (default is 1). |
cen |
A centering value (e.g., a reference exposure level). |
ci.level |
The credible interval level (default |
cumul |
Logical; if |
Details
The function identifies which coefficients in models$fixed[[mod_id]]
and which rows/columns in models$vcov[[mod_id]] correspond to the
one-basis or cross-basis terms (i.e., matching the column names in
basis).
Then it passes these slices to dlnm::crosspred to
generate predictions. The centering value (cen), if specified,
indicates the reference exposure (e.g., a mean temperature) at which to
center the effect estimates (e.g., the effect a given temperature value on
the outcome will be compared to the effect of the centering value on the
outcome, in this case the mean temperature).
Credible intervals are not obtained by drawing from the joint posterior of
the fixed effects. Instead, dlnm::crosspred combines the posterior
mean coefficients with the posterior covariance matrix (models$vcov,
itself INLA's Gaussian approximation to the joint posterior of the fixed
effects), then builds a symmetric interval as fit \pm a Gaussian
quantile times the propagated standard error. This is equivalent to a
posterior-sampling-based interval as long as the joint posterior of the
fixed effects is itself approximately Gaussian and does not reflect any
skewness in the individual marginal posteriors.
Value
An object of class "GHRcrosspred", inheriting from
"crosspred", with fields for the predicted values, credible intervals,
and optionally cumulative predictions, as determined by
crosspred.
See Also
dlnm::crosspred for details on how
predictions are computed.
Examples
# Load example GHRmodels object from the package
model_dlnm_file <- system.file("examples", "model_dlnm.rds",
package = "GHRmodel")
model_dlnm <- readRDS(model_dlnm_file)
# Load example cross-basis matrix from the package: 2-dimensional
# cross-basis matrix of the non-linear effect of dengue risk across
# tmin values and lags:
cb_tmin_file <- system.file("examples", "cb_tmin.rds", package = "GHRmodel")
cb_tmin <- readRDS(cb_tmin_file)
# Generate predictions
pred_result <- crosspred_inla(
models = model_dlnm,
basis = cb_tmin,
mod_id = "mod3",
cen = 20
)
# Inspect predictions
pred_result$predvar # the sequence of 'at' values
pred_result$allfit # fitted values
pred_result$alllow # lower CI
pred_result$allhigh # upper CI
Compute the empirical Continuous Ranked Probability Score (CRPS)
Description
Computes the CRPS for a single observation given a set of posterior predictive draws, using the empirical (energy form) estimator
\mathrm{CRPS} = \frac{1}{n} \sum_{i=1}^n |x_i - y| -
\frac{1}{2n^2} \sum_{i=1}^n \sum_{j=1}^n |x_i - x_j|
where y is the observed value and x_1, \dots, x_n are the
posterior predictive draws. Missing draws in pred_pdd are dropped
before computation.
Usage
crps_empirical(y, pred_pdd)
Arguments
y |
A single numeric observed value. Returns |
pred_pdd |
A numeric vector of posterior predictive draws for the
observation. Returns |
Value
A single numeric CRPS value (or NA_real_, see above).
References
Gneiting, T. and Raftery, A. E. (2007). Strictly Proper Scoring Rules, Prediction, and Estimation. Journal of the American Statistical Association, 102(477), 359-378. (Defines the energy-form representation of the CRPS used here, their eq. 21.)
Zamo, M. and Naveau, P. (2018). Estimation of the Continuous Ranked
Probability Score with Limited Information and Applications to Ensemble
Weather Forecasts. Mathematical Geosciences, 50(2), 209-234.
(Calls this the "NRG" estimator, dividing the pairwise term by n^2
rather than n(n-1); see that paper for the alternative, less
biased "fair"/PWM estimator.)
Dengue cases from the "Mato Grosso do Sul" state of Brazil
Description
The dengue_MS example data set contains monthly counts of notified
dengue cases by microregion, along with a range of spatial and
spatiotemporal covariates (e.g., environmental, socio-economic and
meteo-climatic factors). This data set represents a subset of a
larger national data set that covers the entire territory of Brazil.
The subset focuses on a specific region, Mato Grosso do Sul, for
the purposes of illustration and computational efficiency. See
the source below for access to the complete data set.
Usage
dengue_MS
Format
A data frame with 2,640 rows and 28 columns:
micro_codeUnique ID number to each micro region (11 units)
micro_nameName of each micro region
micro_name_ibgeName of each micro region following IBGE
meso_codeUnique ID number to each meso region (4 units)
meso_nameName of each meso region
state_codeUnique ID number to each state (1 unit)
state_nameName of each state
region_codeUnique ID number given to each Brazilian Region, In this data frame all observations come from the "Centre-West"
region_nameName of each Brazilian Region, In this data frame all observations come from the "Centre-West"
biome_codeBiome code
biome_nameBiome name
ecozone_codeEcozone code
ecozone_nameEcozone name
main_climateMost prevalent climate regime in the microregion. Based on Koppen Geiger climate regimes
monthCalendar month index, 1 = January, 12 = December
yearYear 2000 - 2019
timeTime index starting at 1 for January 2000
dengue_casesNumber of notified dengue cases registered in the notifiable diseases system in Brazil (SINAN) in the microregion of reference, at the month of first symptoms
populationEstimated population, based on projections calculated using the 2000 and 2010 censuses, and counts taken in 2007 and 2017
pop_densityPopulation density (number of people per km2)
tmaxMonthly average daily maximum temperature; gridded values (at a 0.5 deg resolution) averaged across each microregion
tminMonthly average daily minimum temperature; gridded values (at a 0.5 deg resolution) averaged across each microregion
pdsiSelf-calibrated Palmer drought severity index for each microregion. It measures how wet or dry a region is relative to usual conditions. Negative values represent periods of drought, positive values represent wetter periods. Calculated by taking the mean value within each microregion
urbanPercentage of inhabitants living in urban areas (2010 census)
water_networkPercentage of inhabitants with access to the piped water network according to the 2010 census
water_shortageFrequency of reported water shortages per microregion between 2000 - 2016
dateFirst day of the Month, in date format ("%Y-%m-%d")
pop100000Population divided by 100000.
Source
source code on GitHub; source code on Zenodo;
Dengue cases from the "São Paulo" state of Brazil
Description
The dengue_SP example data set reports the weekly number of notified dengue
cases in the municipality of São Paulo together with climatic covariates.
Data was sourced from Infodengue (see source below).
Usage
dengue_SP
Format
A data frame with 624 rows and 9 columns:
dateFirst day of the week, in date format ("%Y-%m-%d")
geocodeIBGE municipality code for the city of São Paulo
casesNumber of notified dengue cases
yearYear 2010 - 2021
temp_medWeekly average daily mean temperature
precip_totWeekly cumulative precipitation
ensoEl Niño-Southern Oscillation Index
popNumber of inhabitants
pop100000Population divided by 100000.
Source
Extract Covariate Names
Description
This function allows the user to select variables from a data set by prefix
(using the pattern argument) or by exact name matching.
The return object is a character vector with the selected covariate names
that can be used as input for cov_add, cov_uni,
cov_multi, cov_interact, cov_nl,
and cov_varying functions.
Usage
extract_names(data = NULL, pattern = NULL, name = NULL)
Arguments
data |
A |
pattern |
A character vector specifying prefix(es) to match (e.g., "tmin" matches "tmin", "tmin.l1", etc.). |
name |
A character vector of exact variable name(s) to extract. |
Value
A character vector of matched covariate names.
Examples
data <- data.frame(tmin = 1:10, tmin.l1 = 1:10, urban = 1:10)
extract_names(data, pattern = "tmin")
extract_names(data, name = "urban")
extract_names(data, pattern = "tmin", name = "urban")
Fit Multiple INLA Models
Description
This function fits a set of INLA model formulas, provided in a
GHRformulas object, to a specified dataset. For each fitted model,
it extracts a range of outputs, including goodness-of-fit (GoF) metrics
and other model outputs (fitted values, fixed effects, random effects).
Results are extracted and stored in a GHRmodels object.
Usage
fit_models(
formulas,
data,
family,
name = "mod",
offset_var = NULL,
control_compute = list(config = FALSE, vcov = FALSE),
control_inla = list(strategy = "adaptive"),
control_family = list(),
ppd_samples = 500,
keep_ppd = FALSE,
keep_inlamod = FALSE,
nthreads = 1,
progress = FALSE,
verbose = FALSE,
offset = NULL
)
Arguments
formulas |
Either a |
data |
A data frame containing the variables used in the model formulas. |
family |
A character string specifying the likelihood family. Currently
available options include |
name |
Either a single character string to label each fitted model
by attaching a count (e.g., |
offset_var |
A character string specifying the name of the offset
variable in |
control_compute |
A named list controlling additional computation
options passed to INLA's
Note that other elements of |
control_inla |
Parameters passed to |
control_family |
Parameters passed to |
ppd_samples |
Numeric indicating the number of posterior predictive
samples to draw. Only used if |
keep_ppd |
Default is FALSE (do not keep ppd). If TRUE (requires
also |
keep_inlamod |
Logical. Default is FALSE. If TRUE, the fitted INLA model objects are stored in the output list, which may result in a substantially larger object. |
nthreads |
An integer specifying the maximum number of threads for
parallel computation. Default is |
progress |
Logical; if |
verbose |
Logical; if |
offset |
Deprecated, use offset_var instead. |
Details
This function iterates over each formula in the GHRformulas object
and fits the corresponding INLA model using the internal function
.fit_single_model(). For each fitted model, it extracts the fitted
values, fixed effects, and random effects summaries. Then, it calculates a
series of model evaluation metrics using the .gof_single_model()
internal function.
Because the first formula is used as the reference model for all
comparison metrics (see Section B below), if it fails to fit,
fit_models() stops and no results are returned for any model.
However, if a formula after the first fit fails, a message is
printed and that model is skipped (GoF row is filled with NA
and object components are left empty).
The goodness-of-fit (GoF) metrics are organized into two categories:
A) Model-Specific Goodness-of-Fit Metrics
These are computed separately for each model:
-
Deviance Information Criterion (DIC)
DIC = \bar{D} + p_{D}where
\bar{D}is the posterior mean deviance andp_{D}is the effective number of parameters. Lower DIC values indicate a better model fit, balancing goodness-of-fit and model complexity. -
Watanabe-Akaike Information Criterion (WAIC)
WAIC = -2\left(\mathrm{lppd} - p_{\mathrm{WAIC}}\right)WAIC evaluates predictive accuracy and penalizes model complexity through the log pointwise predictive density (
\mathrm{lppd}). Lower values imply better generalization. -
Log Mean Score (LMS)
LMS = \frac{1}{n} \sum_{i=1}^n \left( -\log(\mathrm{CPO}_i) \right)LMS assesses the average negative log-predictive density using Conditional Predictive Ordinates (CPO). Lower LMS values indicate stronger predictive performance by penalizing models that assign low probability to observed outcomes.
-
Mean Absolute Error (MAE)
MAE = \frac{1}{n} \sum_{i=1}^n \left| y_i - \hat{y}_i \right|Average absolute difference between observed and a point estimate of the predictions. As a point estimate, it uses the
summary.fitted.valuesprovided by INLA whenconfig = FALSEand the mean of the ppd ifconfig = TRUE. MAE is more robust to outliers than RMSE. Lower MAE values indicate improved model fit. -
Root Mean Squared Error (RMSE)
RMSE = \sqrt{ \frac{1}{n} \sum_{i=1}^n (y_i - \hat{y}_i)^2 }Root average squared difference between observed and a point estimate of the predictions. As a point estimate, it uses the
summary.fitted.valuesprovided by INLA whenconfig = FALSEand the mean of the ppd ifconfig = TRUE. RMSE penalizes larger errors more heavily. Lower RMSE values reflect better model fit. -
Continuous Ranked Probability Score (CRPS)
\mathrm{CRPS}(F, y) = \int_{-\infty}^{\infty} \left[F(t) - \mathbf{1}\{y \leq t\}\right]^2 dtThe intergral is approximated with the empirical CRPS (see crps_empirical):
\mathrm{CRPS} = \frac{1}{n} \sum_{i=1}^n |x_i - y| - \frac{1}{2n^2} \sum_{i=1}^n \sum_{j=1}^n |x_i - x_j|CRPS assesses how well the entire posterior predictive distribution aligns with the observed outcome. The median CRPS across observations is returned. Lower scores suggest better calibrated predictive distributions. Only available when
config = TRUE.
B) Model Comparison Metrics (relative to the first model)
The first model in the list is treated as the baseline for model comparisons. All other models are evaluated against it using the following metrics:
-
Difference in DIC and WAIC Stored as
dic_vs_firstandwaic_vs_first. These represent how much higher (or lower) each model's DIC/WAIC is compared to the first model. Additionally, 95% credible intervals for these differences are stored as*_vs_first_lciand*_vs_first_uci. -
Difference in MAE and RMSE Stored as
mae_vs_firstandrmse_vs_first. These reflect the absolute difference in prediction error compared to the first model. No credible intervals are computed for these metrics. -
Continuous Ranked Probability Score Skill Score (CRPSS)
\mathrm{CRPSS} = 1 - \frac{\mathrm{CRPS}_{\text{model}}}{\mathrm{CRPS}_{\text{baseline}}}Indicates how much better the predictive distribution of the current model is relative to the baseline model. Values closer to 1 indicate improvement; negative values imply worse performance. Available only when
config = TRUE. -
Pseudo R-squared based on deviance
R^2 = 1 - \exp\left( \frac{-2}{n} \left( \frac{dev_{\text{model}}}{-2} - \frac{dev_{\text{base}}}{-2} \right) \right)Captures relative deviance reduction compared to the baseline model. Values range from 0 (no improvement) to 1 (strong improvement).
-
Random Effect Variance
\mathrm{Var}_{re} = \frac{1}{\mathrm{precision}}Quantifies residual variance due to group- or cluster-level effects. Computed only when random effects are defined in the model formula.
-
Proportional Change in Random Effect Variance
\frac{\mathrm{Var}_{re}}{\mathrm{Var}_{re}^{(1)}} - 1Represents the relative change in group-level variance compared to the baseline model. Helps assess how much variance is explained by added covariates.
re1_var_changerefers to the change in specific random effects (ordered by number) whereasre_meanchangeis the mean change across all random effects.re_meanchangeisNAwhen no random effects are defined or if the variance change of any individual random effect isNA.
Value
An object of class GHRmodels containing:
$mod_gofA data frame of model-specific goodness-of-fit metrics.
$fittedA list of fitted values (one element per model). If
config = TRUE, these are derived from the posterior predictive distribution (PPD); otherwise, they are extracted from INLA'ssummary.fitted.values.$fixedA list of summary tables for fixed effects (one element per model).
$randomA list of summary tables for random effects (one element per model).
$vcovA list of variance-covariance (correlation) matrices of fixed effects (one element per model). Populated only when
control_compute$vcov = TRUE.$formulasA character vector of the original model formulas used.
$reA character vector specifying any random effects defined in
formulas.$outcomeA character string indicating the outcome variable used.
$familyA character string indicating the likelihood family used.
$dataThe original data frame passed to the function.
$ppd(if
keep_ppd=TRUE) A list of ppd matrices where rows are observations in the same order as indataand columns are ppd samples.$inlamod(if
keep_inlamod=TRUE) A list of inla model objects.
See Also
as_GHRformulas converts a set of R-INLA-compatible formulas
into a GHRformulas object.
Examples
# Load example dataset
data(dengue_MS)
dengue_MS <- dengue_MS[dengue_MS$year %in% 2010:2012, ]
# Declare formulas
formulas <- c(
"dengue_cases ~ tmin + f(year, model='rw1')",
"dengue_cases ~ pdsi + f(year, model='rw1')"
)
# Fit multiple models
results <- fit_models(
formulas = formulas,
data = dengue_MS,
family = "nbinomial",
name = "TestModel",
offset_var = "pop100000",
nthreads = 2,
progress = TRUE
)
# Inspect goodness-of-fit metrics
results$mod_gof
Retrieve Covariates from a GHRmodels Object as a List of Character Vectors
Description
Extracts covariates from a GHRmodels object and returns them as a list of
character vectors. If unique = TRUE, the output contains unique covariates
across models. If unique = FALSE, the output preserves the original
combinations of covariates as specified in the GHRmodels object.
Usage
get_covariates(model, unique = TRUE)
Arguments
model |
A |
unique |
Logical; if |
Value
A list of character vectors.
Examples
# Load example dataset
data(dengue_MS)
dengue_MS <- dengue_MS[dengue_MS$year %in% 2015:2016,]
# Declare formulas
formulas <- c(
"dengue_cases ~ tmin + f(year, model='rw1')",
"dengue_cases ~ pdsi + f(year, model='rw1')"
)
# Tranform formulas into a 'GHRformulas' object
ghr_formulas <- as_GHRformulas(formulas)
# Fit multiple models
results <- fit_models(
formulas = ghr_formulas,
data = dengue_MS,
family = "nbinomial",
name = "TestModel",
offset_var = "pop100000",
nthreads = 2,
control_compute = list(config = FALSE),
progress = TRUE
)
# Extract the list of covariates from the models
get_covariates(results)
Generate lagged variables for one or more lags
Description
This function creates lagged versions of one or more numeric or categorical variables in an equally spaced time-series data set. A single call can create multiple lags for each selected variable and, optionally, for each spatial/grouping unit.
Usage
lag_cov(data, name, time, lag, group = NULL, add = TRUE)
Arguments
data |
A |
name |
A character vector: name of the variable (or variables) to lag. |
time |
A single character string: name of the time-index variable (e.g.,
|
lag |
A numeric vector of one or more positive integers. Each value is
interpreted as a 'lag' (i.e. shift the series backward by |
group |
Optional character vector naming a column that define
independent time-series (e.g. regions). If |
add |
Logical. If |
Value
Either a data frame (when add = TRUE) containing the original
data plus the new lagged columns, or a numeric matrix of lagged values
(when add = FALSE).
Examples
## Daily series for two micro-regions
d <- data.frame(
date = as.Date("2023-01-01") + 0:9,
micro_code = rep(c("A", "B"), each = 5),
tmin = rnorm(10, 10, 2),
pdsi = rnorm(10)
)
## Create lags 1 to 3 for tmin and pdsi
lagged <- lag_cov(
data = d,
name = c("tmin", "pdsi"),
time = "date",
group = "micro_code",
lag = c(1:3)
)
## Only lagged columns (matrix),
lag_only <- lag_cov(
data = d, name = "tmin", time = "date",
lag = c(1:3), add = FALSE
)
Administrative boundaries of Mato Grosso do Sul
Description
Administrative boundaries (polygon geometries) of the 11 municipalities
in Mato Grosso do Sul (Brazil) to be used with the dengue_MS data set.
Usage
data(map_MS)
Format
A simple feature (sf) object including 11 rows and 2 columns:
- code
Unique ID number to each micro region (11 units).
- geometry
Geometries of the sf multipolygon.
Create a One-Dimensional Basis for INLA
Description
This function is a wrapper around onebasis to
create a one-dimensional basis for spline modeling. This wrapper enhances the
original function by allowing users to specify a custom prefix for the column
names using the basis_name argument, such that each set of basis variables
can be easily identified in the model formula by the INLA framework.
Usage
onebasis_inla(covariate, fun, basis_name, ...)
Arguments
covariate |
A numeric vector representing the covariate. |
fun |
A character string specifying the shape function to be used by
|
basis_name |
A character string giving a base name for the columns in
the resulting basis matrix. The default prefix |
... |
Additional arguments passed to |
Value
An object of class "onebasis", as returned by
onebasis, with column names modified according to
basis_name.
Examples
# Import example data set
data("dengue_MS")
# Build a one-dimensional spline basis with a custom name
ob_inla <- onebasis_inla(
covariate = dengue_MS$tmin,
fun = "bs",
basis_name = "tempBasis",
degree = 2
)
# Check class of the one-basis object
class(ob_inla)
# View first rows of the one-basis matrix
head(ob_inla)
Plot crosspred Objects: Overall, Slices, or Heatmap
Description
Generate plots from a "crosspred" object.
Three plot types are available:
-
type = "overall": Shows the overall exposure–response relationship, aggregated across all lags. -
type = "slices": Produces line plots with credible interval ribbons, either across lags (for a fixedvar) or across values ofvar(for a fixedlag). -
type = "heatmap": Displays a two-dimensional heatmap of effects across bothvarandlag. Not applicable for one-basis models.
Usage
plot_coef_crosspred(
crosspred,
type = c("heatmap", "slices", "overall"),
var = NULL,
lag = NULL,
exp = FALSE,
palette = "-RdBu",
n_lag_smooth = 50,
line_color = "black",
line_size = 0.7,
ribbon_color = NULL,
ribbon_alpha = 0.2,
heat_lims = NULL,
title = "",
ylab = NULL,
xlab = NULL,
...
)
Arguments
crosspred |
An object of class |
type |
Character string. Options: |
var |
Optional numeric vector of exposure values (used when
|
lag |
Optional numeric vector of lag values (used when
|
exp |
Logical. If |
palette |
Character string for heatmap palette when
|
n_lag_smooth |
Integer, number of interpolation points along lag for heatmap smoothing (default = 50). |
line_color |
Character string. Line color when |
line_size |
Numeric. Line width (default = 0.7). |
ribbon_color |
Character string. Color for credible interval ribbons.
Defaults to |
ribbon_alpha |
Numeric. Alpha transparency for ribbons (default = 0.2). |
heat_lims |
Numeric vector of length 2 indicating the lower and upper
limits of the colour scale when |
title |
Character string. Plot title. |
ylab |
Character string. Label for y-axis. |
xlab |
Character string. Label for x-axis. |
... |
Additional arguments passed to |
Value
A ggplot object for the specified plot type.
See Also
Examples
# Load example GHRmodels object from the package
model_dlnm_file <- system.file("examples",
"model_dlnm.rds",
package = "GHRmodel")
model_dlnm <- readRDS(model_dlnm_file)
# Load example cross-basis matrix from the package:
# 2-dimensional cross-basis matrix of the
# non-linear effect of dengue risk across tmin values and lags:
cb_tmin_file <- system.file("examples","cb_tmin.rds", package = "GHRmodel")
cb_tmin <- readRDS(cb_tmin_file) # loads cross-basis matrix
# Generate predictions
pred_result <- crosspred_inla(
models = model_dlnm,
basis = cb_tmin,
mod_id = "mod3",
at = seq(17, 24, by = 1), # e.g., temperature sequence
cen = 20,
ci.level = 0.95
)
# Plot DLNM predictions
plot_coef_crosspred(
crosspred = pred_result, # Crosspred object with model predictions
type = "slices", # Plot specific slices of exposure-response
exp = TRUE, # Exponentiate coefficients (relative risk scale)
var = c(22:24), # Display results for temperature 22°C to 24°C
line_color = "red", # Red color for the effect estimates lines
line_size = 0.8, # Line thickness set to 0.8 for better visibility
ribbon_color = "red", # Red shading for credible interval ribbons
ribbon_alpha = 0.3, # Set ribbon transparency to 30%
title = "Effect of minimum temp. 22°C to 23°C on dengue RR by lag",
xlab = "Lag", # Label for the x-axis (exposure variable)
ylab = "Relative Risk (RR)" # Label for the y-axis (effect estimate scale)
)
Produce a Forest Plot of Linear Covariates from a GHRmodels Object
Description
This function extracts fixed-effect coefficients from a specified model
in models, filters them by name or interaction pattern, and
produces a forest plot (point estimates with error bars).
If
name = NULL, all fixed-effect terms (excluding the intercept) are shown.If
nameis a character vector, only the matching terms are included.
Usage
plot_coef_lin(
models,
mod_id = NULL,
name = NULL,
pattern = NULL,
title = NULL,
mod_label = NULL,
var_label = NULL,
palette = "IDE2",
exp = FALSE,
legend = "Model"
)
Arguments
models |
An object of class |
mod_id |
Character vector of model identifiers (must match entries in
|
name |
A character vector specifying exact linear covariates names
to be plotted. If both |
pattern |
A character vector specifying prefix(es) to match (e.g.,
"tmin" matches "tmin", "tmin.l1", etc.). Covariates matching these
patterns (case‐insensitive search) will be plotted. If both
|
title |
An optional string specifying an overall plot title. |
mod_label |
An optional named character vector mapping model names to custom labels, e.g. c("mod1" = "Model 1"). Any model not found in the vector names retains its original label. |
var_label |
An optional named character vector mapping variable
(or interaction) names to custom labels. Interaction matching is
order-insensitive: |
palette |
GHR, RColorBrewer or colorspace palette (e.g. "Purp") colour
palette to use for the different models. See all available options by running
|
exp |
Logical,if |
legend |
Legend title for the replicate color scale. Default is
|
Details
- Intercept
By default,
(Intercept)is excluded unless explicitly included inname.- Individual terms
e.g.,
"temp".- Interaction Terms
e.g.
"temp:precip". Split by:, sorted, and compared setwise; for example,"temp:precip"matches"precip:temp".- Labels
If
var_labelis supplied, any matched covariate or interaction string is replaced by its custom label on the y-axis.
Value
A ggplot2 forest plot object (class ggplot).
Examples
# Load example GHRmodels object from the package:
model_list_file <- system.file("examples", "model_list.rds",
package = "GHRmodel")
model_list <- readRDS(model_list_file)
# Plot point estimates with confidence intervals for the linear covariates:
plot_coef_lin(
model = model_list,
mod_id = c("mod2","mod4"),
var_label = c("tmin.l1"= "Min. temp lag 1",
"pdsi.l1" = "Drought index lag 1"),
title = "Effects of linear covariates"
)
Plot Nonlinear Effects from a GHRmodels Object
Description
Generates plots of nonlinear effects from one or more fitted models contained
within a GHRmodels object. The function supports two main display modes:
Grid (when
collapse = FALSE): one plot per covariate and model, with effects by column and models by row.If multiple models are specified, the user must provide either
nameorpatternto select which nonlinear effects to plot.If only one model is selected and both
nameandpatternareNULL, all nonlinear effects in the model will be plotted.
Collapsed (when
collapse = TRUE): one non-linear effect combined across models into a single panel.The user must explicitly specify the exact variable name using
name. It only accepts one covariate name.Collapse mode can only be used when the selected effect is not replicated (that is, does not have the format
f(covariate, model = ..., replicate = group)). If replication is detected, an error will be thrown.
Usage
plot_coef_nl(
models,
mod_id,
mod_label = NULL,
name = NULL,
pattern = NULL,
title = NULL,
var_label = NULL,
palette = "IDE2",
xlim = NULL,
ylab = NULL,
xlab = NULL,
histogram = FALSE,
legend = NULL,
hist_fill = "grey",
rug = FALSE,
collapse = FALSE,
exp = FALSE
)
Arguments
models |
A |
mod_id |
Integer vector specifying which model(s) to plot (as indexed in
|
mod_label |
An optional named character vector mapping model names to custom labels, e.g. c("mod1" = "Model 1"). Any model not found in the vector names retains its original label. |
name |
Optional character vector of variable names (as used in
|
pattern |
Optional regular expression pattern to match effect names.
Used to select nonlinear effects when |
title |
Optional overall title for the plot. |
var_label |
Optional named character vector providing custom labels for
each nonlinear variable. Names must match the variable names (e.g., used in
|
palette |
Name of the color palette to use (passed to
|
xlim |
Optional named list specifying x-axis limits for each effect.
Each element should be a numeric vector of length 2:
|
ylab |
Optional y-axis label. If |
xlab |
Optional x-axis label. If |
histogram |
Logical; if |
legend |
Legend title for the replicate color scale (if multi-replicate
effects are present). Default is |
hist_fill |
Fill color for histogram bars. Default is |
rug |
Include a rug plot in the x-axis. Default is FALSE. |
collapse |
Logical; if |
exp |
Logical,if |
Value
A ggplot or cowplot object, depending on the plotting
mode.
Examples
# Load example GHRmodels object from the package:
model_list_file <- system.file("examples", "model_list.rds",
package = "GHRmodel")
model_list <- readRDS(model_list_file)
# Plot 2 models with non-linear PDSI at one month lag in collapsed mode:
plot_coef_nl(
models = model_list,
mod_id = c( "mod5", "mod6") ,
mod_label = c("mod6" = "pdsi.l1_nl",
"mod5" = "pdsi.l1_nl + tmin.l1_nl"),
var_label = c("pdsi.l1" = "Drought index (PDSI)"),
name = c("pdsi.l1"),
title = "Change in PDSI with and without mean min. temp lag 1",
xlab = "PDSI",
palette = "IDE2",
collapse = TRUE
)
Produce a Forest Plot for a Spatially or Temporally Varying Effects from
a GHRmodels object.
Description
Generates a forest plot for a specified spatially or temporally varying
coefficient (i.e. a random slope) from a fitted GHRmodels object. The plot
displays the effect estimates (x-axis) for each spatial/temporal unit
(y-axis).
Usage
plot_coef_varying(
models,
mod_id,
name,
unit_label = NULL,
palette = "IDE2",
title = NULL,
xlab = "Effect size",
ylab = NULL,
exp = FALSE
)
Arguments
models |
A |
mod_id |
A character specifying which model to be plotted (as in
|
name |
A character string naming the spatially or temporally varying
coefficient to plot. This should match a random effect name in
|
unit_label |
Optional named character vector providing custom labels for each spatial/temporal unit. |
palette |
Character string for the GHR, RColorBrewer or colorspace
palette (e.g. "Purp") colour palette to use for the different models.
See all available options by running |
title |
Optional string for the plot title. |
xlab |
Optional character string for the x-axis label (default = "Effect size"). |
ylab |
Optional character string for the y-axis label (default constructed from varying covariate name). |
exp |
Logical,if |
Value
A ggplot2 forest plot object representing the spatially or
temporally varying effect, with each line corresponding to a different
spatial or temporal unit.
Examples
# Load example GHRmodels object from the package:
model_cov_list_file <- system.file("examples", "model_cov_list.rds",
package = "GHRmodel")
model_cov_list <- readRDS(model_cov_list_file)
plot_coef_varying(
models = model_cov_list, # A list of fitted INLA model objects
mod_id = "mod8", # Select the model with varying slopes
palette = "Blues", # Color palette for the plot
name = "main_climate_f", # The grouping variable
title = "Effect of PDSI at one-month lag for each climate zone",
ylab = "Main climate zones", # Label for the y-axis
unit_label = c( # Map factor levels to descriptive names
"1" = "Tropical Rainforest Climate",
"2" = "Tropical Monsoon Climate",
"3" = "Tropical Savanna Climate with Dry Winter",
"4" = "Humid Subtropical Climate")
)
Plot Observed vs. Fitted Cases
Description
This function creates a time series plot comparing observed cases with fitted
values (i.e., mean predicted counts) from one or more models in a
GHRmodels object.
Usage
plot_fit(
models,
mod_id = NULL,
time = NULL,
unit = NULL,
unit_id = NULL,
ci = FALSE,
aggregate_space = NULL,
mod_label = NULL,
palette = "IDE2",
ref_color = NULL,
obs_color = NULL,
obs_label = NULL,
title = "",
transform = "identity",
xlab = "Time",
ylab = "Cases",
xlim = NULL,
legend = "Model"
)
Arguments
models |
A |
mod_id |
Character vector of model identifiers (from
|
time |
Character; name of the time variable column in
|
unit |
Optional; character name of the column in
|
unit_id |
Optional character vector of specific unit values to subset if
|
ci |
Logical; if |
aggregate_space |
Name of variable used to define spatial
aggregation groups that contain the different units. Counts within
that aggregation group will be summed. Use |
mod_label |
Optional custom labels for each model. Can be a named
vector (e.g., |
palette |
Character; name of the color palette for fitted lines.
Default is |
ref_color |
Optional color to override the first model's line (reference model). |
obs_color |
Color for observed data line. Default is |
obs_label |
Legend label for observed data. Default is
|
title |
Character; title of the plot. |
transform |
Character string for y-axis transformation. Defaults
to |
xlab |
Label for the x-axis. Default is |
ylab |
Label for the y-axis. Default is |
xlim |
Date vector of length two (e.g., |
legend |
Legend title for model lines. Default is |
Value
A ggplot2 object with the time series line plot of observed
vs fitted cases.
See Also
fit_models to generate GHRmodels.
Examples
# Load example GHRmodels object from the package:
model_list_file <- system.file("examples", "model_list.rds",
package = "GHRmodel")
model_list <- readRDS(model_list_file)
# Plot observed vs. fitted cases over time for three selected models
plot_fit(
models = model_list,
mod_id = c("mod1", "mod3", "mod5"),
mod_label = c("Baseline", "tmin.l1.nl", "pdsi.l1.nl_tmin.l1.nl"),
time = "date",
unit = "micro_name",
xlim = as.Date(c("2015-01-01", NA))
)
Plot Models by Goodness-of-Fit
Description
Provides visualization of model performance using selected goodness-of-fit
(GoF) metrics for one or more models. It is typically used with the
mod_gof component of a GHRmodels object (produced by
fit_models), but it can also accept any custom
data frame — provided it contains the same column names as the default
mod_gof output (including model_id and the relevant metric column names).
It supports visual grouping by aesthetics (color, shape, facet), arranging
models by metric, and adding credible intervals for model differences.
Usage
plot_gof(
mod_gof,
metric = "dic",
mod_id = NULL,
mod_label = NULL,
ci = FALSE,
var_arrange = NULL,
var_color = NULL,
var_shape = NULL,
var_facet = NULL,
palette = "IDE2",
title = "",
xlab = NULL,
ylab = NULL,
legend = NULL
)
Arguments
mod_gof |
A data frame containing goodness-of-fit statistics for
each model. Typically this is the |
metric |
Character string specifying the GoF metric to plot. Common options include:
|
mod_id |
Optional character vector of model IDs to include. If
|
mod_label |
Optional named or unnamed vector to customize display
names for models. If unnamed, must match the order of |
ci |
Logical. If |
var_arrange |
Character string for a column name used to order
models along the x-axis. Defaults to |
var_color |
Optional; name of a column in |
var_shape |
Optional; name of a column in |
var_facet |
Optional; name of a column in |
palette |
Character; name of a color palette to use if
|
title |
Character; title of the plot. Default is |
xlab |
Label for the x-axis. If |
ylab |
Label for the y-axis. If |
legend |
Legend title for the color and shape legends. If |
Details
This function helps interpret and visualize comparative model performance:
Relative metrics (e.g.,
"*_vs_first") assume the first model is a reference.If
ci = TRUE, the function looks for columns like"dic_vs_first_lci"and"_uci".The user can customize model order with
var_arrangeand legend groupings usingvar_color, etc.
Value
A ggplot2 object showing the specified metric for each
model, optionally grouped and faceted.
The plot supports:
Ranking or sorting models by a specified variable
Highlighting credible intervals for relative metrics (e.g.
"dic_vs_first")Group-level comparisons via color, shape, and facet aesthetics
See Also
fit_models for fitting multiple INLA models.
Examples
# Load example GHRmodels object from the package:
model_list_file <- system.file("examples", "model_list.rds",
package = "GHRmodel")
model_list <- readRDS(model_list_file)
# Plot models by difference in DIC
plot_gof(mod_gof = model_list$mod_gof,
metric = "dic_vs_first",
ci = TRUE,
var_arrange = "dic",
var_color = "model_id",
palette= "IDE2")
Plot Posterior Predictive Densities Versus Observed Data
Description
This function draws kernel-density curves for posterior-predictive samples
and observed data using ggplot2::geom_line(). Each predictive
sample’s density is plotted in light blue; the observed density is overlaid
in black.
Usage
plot_ppd(
ppd,
obs,
xlab = "Outcome",
ylab = "Density",
title = "Posterior Predictive Distribution",
xlim = NULL,
obs_color = NULL,
ppd_color = NULL
)
Arguments
ppd |
A |
obs |
A vector of observations, must have the same length as the
number of columns in |
xlab |
Character: x-axis label. Default |
ylab |
Character: y-axis label. Default |
title |
Character: plot title. Default
|
xlim |
Numeric vector of length 2 giving the minimum and maximum
x-axis values, e.g. |
obs_color |
Color for the observed line density. |
ppd_color |
Color for the posterior predictive distribution line density. |
Value
A ggplot2 plot object.
Examples
# Load example dataset
data(dengue_MS)
dengue_MS <- dengue_MS[dengue_MS$year %in% 2015:2016,]
# Declare formulas
formulas <- "dengue_cases ~ tmin + f(year, model='rw1')"
# Tranform formulas into a 'GHRformulas' object
ghr_formula <- as_GHRformulas(formulas)
# Fit multiple models
results <- fit_models(
formulas = ghr_formula,
data = dengue_MS,
family = "nbinomial",
name = "model",
offset_var = "pop100000",
nthreads = 2,
control_compute = list(config = TRUE),
keep_ppd = TRUE,
ppd_samples = 50
)
# Plot densities of the posterior predictive distribution and observed cases.
plot_ppd(results$ppd[[1]], obs = dengue_MS$dengue_cases)
Plot Random Effects
Description
Generates plots of random effects from one or more fitted models contained
within a GHRmodels object. The function supports two main display modes:
Caterpillar plot of effect sizes with uncertainty intervals (the default).
Choropleth map (when a spatial map (
sfobject) is provided in themapargument).
It also supports visualization of replicated or grouped effects via the
rep_id argument.
Usage
plot_re(
models,
mod_id,
re_id,
rep_id = NULL,
map = NULL,
map_unit = NULL,
mod_label = NULL,
re_label = NULL,
rep_label = NULL,
ref_color = NULL,
palette = NULL,
var_arrange = "ID",
title = "",
xlab = "Re ID",
ylab = "Effect Size",
legend = "Effect Size",
centering = 0,
exp = FALSE
)
Arguments
models |
A |
mod_id |
Character vector of model IDs to plot (must match entries in
|
re_id |
Character; name of the variable defining the random effect
(from |
rep_id |
Optional character string; name of a grouping variable if
random effects are replicated. Default is |
map |
Optional |
map_unit |
Character; column name in |
mod_label |
Optional labels for models. Can be a named vector
(e.g., |
re_label |
Optional; variable in the data to label the random effect units (e.g., year names instead of numeric IDs). |
rep_label |
Optional; label for replicated grouping variable (e.g., for years or time periods). |
ref_color |
Color used for the reference model. If specified, this
will apply to the first model in |
palette |
Character; name of the color palette to use. Defaults to
|
var_arrange |
Character; how to arrange REs on the x-axis. Options:
|
title |
Title for the plot. |
xlab |
Label for the x-axis. Default is |
ylab |
Label for the y-axis. Default is |
legend |
Label for the legend in map plots. Default is
|
centering |
Value at which to center the color scale for map plots.
Default is |
exp |
Logical; if |
Details
Plot Random Effects from GHRmodels
If
mapis used,map_unitmust match a column inmapand correspond in order to the RE unit.For BYM/BYM2 models, only the total random effect is plotted (structured/unstructured parts are merged).
When no map is used, the plot compares models via colored points and intervals for each RE unit.
Replicated REs (e.g., for years) can be plotted across facets using
rep_label.Model comparison is visually aided using distinct colors; the first model in
mod_idis the reference.
Value
A ggplot2 plot object:
If
mapisNULL, returns a caterpillar plot showing median REs with 95% uncertainty intervals.If
mapis provided, returns a faceted choropleth map showing RE medians by spatial unit and (optionally) replicate.
See Also
fit_models for model fitting; as_GHRformulas
for formula setup.
Examples
# Load example GHRmodels object from the package:
model_list_file <- system.file("examples", "model_list.rds",
package = "GHRmodel")
model_list <- readRDS(model_list_file)
# Plot the estimated yearly random effects for three different models.
plot_re(
model = model_list, # A GHRmodels object
mod_id = c("mod1", "mod3", "mod5"), # IDs of the models
mod_label = c("Baseline", # Custom labels for the models
"tmin.l1_nl",
"pdsi.l1_nl + tmin.l1_nl"),
re_id = "year_id", # Name of the random effect variable
re_label = "year", # Label to map year_id to calendar years
ref_color = "grey", # Color for the reference model’s effects
palette = "IDE2", # Color for other model effects
title = "Yearly Random Effect", # Title for the plot
xlab = "Year" # Label for the x-axis
)
Fit Multiple INLA Models and sample their predicted vales
Description
This function is a simplified version of fit_models that only keeps predictions for the input data and accepts formula strings with different random effects.
Usage
predict_models(
formulas,
data,
family,
pred_type = "ppd",
name = "mod",
offset_var = NULL,
ppd_samples = 500,
idx = NULL,
control_inla = list(strategy = "adaptive"),
control_family = list(),
nthreads = 1,
progress = TRUE,
verbose = FALSE,
offset = NULL
)
Arguments
formulas |
A string vector containing multiple INLA model formulas.
Can be the |
data |
A data frame containing the variables used in the model formulas. |
family |
A character string specifying the likelihood family. Currently
available options include |
pred_type |
A string indicating the prediction method to use. Options include "ppd" (default), "postmean" and "postmedian". See details. |
name |
Either a single character string to label each fitted model
by attaching a count (e.g., |
offset_var |
A character string specifying the name of the offset
variable in |
ppd_samples |
Numeric indicating the number of posterior predictive
samples to draw. Only used if |
idx |
Default is NULL (keep all data rows). Alternatively, pass a vector of indices indicating the indices of the predictions to be kept. |
control_inla |
Parameters passed to |
control_family |
Parameters passed to |
nthreads |
An integer specifying the maximum number of threads for
parallel computation. Default is |
progress |
Logical; if |
verbose |
Logical; if |
offset |
Deprecated, use offset_var instead. |
Details
The pred_type methods available include:
-
"ppd": Posterior predictive distribution, computed by generating posterior samples usingINLA::inla.posterior.sampleand simulating from the respective likelihood function. -
"postmean": Posterior mean of the fitted mean response, obstained bysummary.fitted.values$meanavailable in the INLA object. -
"postmedian": Posterior median of the fitted mean response, obstained bysummary.fitted.values$0.5quantavailable in the INLA object.
Note that the methods postmean and postmedian are faster than pdd,
but probabilistic scoring metrics cannot be calculated when using them.
Value
A named list with model names according to name, each containing
a matrix with the predictions. The number of rows will be equal to the
number of rows of data (unless idx has been used) and the number of
columns will be equal to ppd_samples for pred_type='ppd' and 1
for the other prediction methods.
See Also
fit_models for model fits with GoF metrics, INLA objects, and other information about the model fit.
Examples
# Load example dataset
data(dengue_MS)
dengue_MS <- dengue_MS[dengue_MS$year %in% 2015:2016,]
# Declare formulas
formula <- "dengue_cases ~ tmin + f(month, model='rw1')"
# 10 ppd samples, keep rows 30 to 49
respred <- predict_models(
formulas = formula,
data = dengue_MS,
family = "nbinomial",
pred_type = "ppd",
name = "TestModel",
offset_var = "pop100000",
ppd_samples = 10,
idx = 30:49
)
Print GHRmodels objects
Description
Generic print function for objects of class GHRmodels.
Usage
## S3 method for class 'GHRmodels'
print(x, ...)
Arguments
x |
An object of type GHRmodels |
... |
other arguments. |
Rank Models by Goodness-of-Fit
Description
This function ranks fitted models in a GHRmodels object by a chosen metric
(e.g., dic, waic, crps, etc.).
Usage
rank_models(models, metric = "dic", n = 10)
Arguments
models |
A |
metric |
A character string indicating which goodness-of-fit metric to
use for ranking. One of: |
n |
An integer specifying how many top-ranked models to return
(default |
Value
A character vector of the top model IDs (in ascending order of the
specified metric).
See Also
fit_models for fitting multiple INLA models.
Examples
# Load example GHRmodels object from the package:
model_list_file <- system.file("examples", "model_list.rds",
package = "GHRmodel")
model_list <- readRDS(model_list_file)
# Get a list of the 5 best models by DIC
top_model_dic <- rank_models(
models = model_list,
metric = "dic",
n = 5
)
top_model_dic
Fixed-effects model selection
Description
Performs a two-stage fixed effect model selection:
Best configuration: Fits, ranks and selects univariable fixed effect models by covariate (rolling averages, lags, non-linear) according to goodness of fit metrics.
Best combination: Generates, fits, and ranks multivariable combinations of the selected univariable fixed effects.
The function returns all intermediate and final results in a structured output list, including generated formulas, goodness-of-fit (GoF) metrics, ranked models, and selected model combinations.
WARNING: This function is experimental. Model selection should combine goodness-of-fit and cross-validation metrics, which will be included in future versions of the functions.
Usage
select_fe(
data,
outcome,
covariates,
time,
unit = NULL,
re_mod,
re_id = NULL,
roll_mean = NULL,
roll_sum = NULL,
lag = NULL,
nl = NULL,
family = "nbinomial",
offset_var = NULL,
metric = c("waic", "lms", "re_meanchange"),
n_select_uni = 1,
n_select_multi = 3,
standardize = "all",
nthreads = 1
)
Arguments
data |
A data.frame containing the outcome and covariates used for model fitting. Should contain columns named "spatial_id", "seasonal_id" and "year_id" if spatial, seasonal, or interannual effects are considered. |
outcome |
Character specifying the outcome variable name. |
covariates |
Names of the covariates in the data to consider. |
time |
Character specifying the name of the column of |
unit |
Character specifying the name of the column of |
re_mod |
Either the output of |
re_id |
Only used if |
roll_mean |
A named list specifying the variables in |
roll_sum |
Same as |
lag |
A named list specifying the variables in |
nl |
A named list specifying the variables in |
family |
Character string specifying the likelihood family
(default is |
offset_var |
A character specifying the name of the offset
variable in |
metric |
Character vector specifying the ranking metric used to rank models. Options include 'waic', 'lms', 're_meanchange' (defaults), 'dic', 'rmse' and 'mae'. See fit_models for more details on the metrics. |
n_select_uni |
Integer. Number of best-fitting univariable models to select per covariate group. |
n_select_multi |
Integer. Number of best-fitting multivariable models to display as final candidates. Note that only combinations with at least length(covariates) - 1) are considered. |
standardize |
Character. Specifies which variables should be standardised, which can help model convergence. Standardization is applied after rolling statistics and before lagging, so that the mean of all non-lagged variables is equal to 0 and standard deviation is 1 (these may vary slightly for lagged versions due to dropped rows). Set to NULL for no standardization, set to 'all' (default) to apply to all covariates or use specific covariate names. |
nthreads |
An integer specifying the maximum number of threads for
parallel computation. Default is |
Value
A list of class GHRselect_fe containing:
-
params: Selection of input parameters used in the reporting of the results. -
data: Data used for all the model runs after transformations. -
fe_uni_mod: Univariable fixed effect models. -
fe_uni_gof: GoF results for univariable fixed effect models. -
fe_uni_selected: Selected univariable fixed effect models. -
fe_multi_gof: GoF results for multivariable fixed effect models. -
fe_multi_mod: Multivariable fixed effect models. -
fe_multi_selected: Selected multivariable fixed effects. -
best: Best-fitting multivariable model formula.
See Also
Examples
## Not run:
# Read data
library(sf)
data(dengue_MS)
dengue_MS <- dengue_MS[complete.cases(dengue_MS), ]
# Compute graph
data(map_MS)
nb <- spdep::poly2nb(map_MS)
g <- spdep::nb2mat(nb, style = "B")
# Prepare indices
dengue_MS$spatial_id <- as.numeric(as.factor(dengue_MS$micro_code))
dengue_MS$seasonal_id <- dengue_MS$month
dengue_MS$year_id <- dengue_MS$year
# Prepare precision priors
prec1 <- list(prec = list(prior = "pc.prec", param = c(0.5, 0.01)))
prec2 <- list(prec = list(prior = "pc.prec", param = c(0.25, 0.01)))
# Run RE model selection
dengue_re <- select_re(
data = dengue_MS,
outcome = "dengue_cases",
prior = c("prec1", "prec2"),
offset_var = "pop100000",
time = "date",
unit = "micro_name"
)
# Generate report
select_report(dengue_re, file.path(tempdir(), "random_effects.html"))
# Run FE model selection
dengue_fe <- select_fe(
data = dengue_MS,
outcome = "dengue_cases",
covariates = c("tmax", "pdsi"),
roll_mean = list(tmax = c(1, 6), pdsi = c(1, 6)),
lag = list(tmax = c(1, 3), pdsi = c(1, 3)),
nl = list(tmax = c(4, 8), pdsi = 8),
offset_var = "pop100000",
time = "date",
unit = "micro_name",
re_mod = dengue_re
)
# Generate report
select_report(dengue_fe, file.path(tempdir(), "fixed_effects.html"))
## End(Not run)
Random-effects model selection
Description
Performs a two-stage random effect model selection:
Best configuration: Fits, ranks and select univariable random effect models by effect type (spatial, seasonal, interannual) according to goodness of fit metrics.
Best combination: Generates, fits, and ranks multivariable combinations of the selected univariable random effects.
The function returns all intermediate and final results in a structured output list, including generated formulas, goodness-of-fit (GoF) metrics, ranked models, and selected model combinations. See details for requirements.
WARNING: This function is experimental. Model selection should combine goodness-of-fit and cross-validation metrics, which will be included in future versions of the functions.
Usage
select_re(
data,
outcome,
prior,
time,
unit = NULL,
re_spatial = "bym2",
re_seasonal = c("rw1", "rw2"),
re_interannual = c("iid", "rw1", "rw2"),
family = "nbinomial",
offset_var = NULL,
metric = c("waic", "lms"),
n_select_uni = 1,
n_select_multi = 3,
nthreads = 1
)
Arguments
data |
A data.frame containing the outcome and covariates used for model fitting. Should contain columns named "spatial_id", "seasonal_id" and "year_id" if spatial, seasonal, or interannual effects are considered. |
outcome |
Character specifying the outcome variable name. |
prior |
Character vector specifying the prior specifications to try for each random effect. A prior with the same name must be present in the working environment (see example). |
time |
Character specifying the name of the column of |
unit |
Character specifying the name of the column of |
re_spatial |
Character specifying the spatial random effect models to
include. Options include "bym2" (default) and NULL (no spatial RE). If not
NULL, an object |
re_seasonal |
Character vector specifying the seasonal random effect
models to include. Options include "rw1", "rw2" and NULL (no seasonal RE).
If not NULL, the seasonal identifier |
re_interannual |
Character vector specifying the interannual random
effect models to include. Options include "iid", "rw1" and "rw2" and NULL
(no interannual RE). If not NULL, the interannual identifier |
family |
Character string specifying the likelihood family
(default is |
offset_var |
A character string specifying the name of the offset
variable in |
metric |
Optional character string specifying the ranking metric
used in |
n_select_uni |
Integer. Number of best-fitting univariable models to select per random effect group. |
n_select_multi |
Integer. Number of best-fitting multivariable models to display as final candidates in the report. |
nthreads |
An integer specifying the maximum number of threads for
parallel computation. Default is |
Value
A named list of class GHRselect_re containing:
-
params: Selection of input parameters used in the reporting of the results. -
data: Data used for all the model runs. -
re_uni_mod: Univariable random effect models. -
re_uni_gof: GoF results for univariable random effect models. -
re_uni_selected: Selected univariable random effects. -
re_multi_mod: Multivariable random effect models. -
re_multi_gof: GoF results for multivariable random effect models. -
re_multi_selected: Selected multivariable random effects. -
best: Best-fitting multivariable model formula.
See Also
Examples
## Not run:
# Read data
library(sf)
data(dengue_MS)
dengue_MS <- dengue_MS[complete.cases(dengue_MS), ]
# Compute graph
data(map_MS)
nb <- spdep::poly2nb(map_MS)
g <- spdep::nb2mat(nb, style = "B")
# Prepare indices
dengue_MS$spatial_id <- as.numeric(as.factor(dengue_MS$micro_code))
dengue_MS$seasonal_id <- dengue_MS$month
dengue_MS$year_id <- dengue_MS$year
# Prepare precision priors
prec1 <- list(prec = list(prior = "pc.prec", param = c(0.5, 0.01)))
prec2 <- list(prec = list(prior = "pc.prec", param = c(0.25, 0.01)))
# Run RE model selection
dengue_re <- select_re(
data = dengue_MS,
outcome = "dengue_cases",
prior = c("prec1", "prec2"),
offset_var = "pop100000",
time = "date",
unit = "micro_name"
)
# Generate report
select_report(dengue_re, file.path(tempdir(), "random_effects.html"))
## End(Not run)
Automatic reporting of GHR model selection functions.
Description
Generates reports of the semi-automatic model selection carried
out by select_re or select_fe. It requires rmarkdown to be
run.
Usage
select_report(select_out, output_file, quiet = TRUE)
Arguments
select_out |
A GHRselect_re generated by select_re or a GHRselect_fe object generated by select_fe. |
output_file |
A character indicating the output file. |
quiet |
Logical; if |
Value
Silent output path where the html report is saved.
See Also
Examples
## Not run:
# Read data
library(sf)
data(dengue_MS)
dengue_MS <- dengue_MS[complete.cases(dengue_MS), ]
# Compute graph
data(map_MS)
nb <- spdep::poly2nb(map_MS)
g <- spdep::nb2mat(nb, style = "B")
# Prepare indices
dengue_MS$spatial_id <- as.numeric(as.factor(dengue_MS$micro_code))
dengue_MS$seasonal_id <- dengue_MS$month
dengue_MS$year_id <- dengue_MS$year
# Prepare precision priors
prec1 <- list(prec = list(prior = "pc.prec", param = c(0.5, 0.01)))
prec2 <- list(prec = list(prior = "pc.prec", param = c(0.25, 0.01)))
# Run RE model selection
dengue_re <- select_re(
data = dengue_MS,
outcome = "dengue_cases",
prior = c("prec1", "prec2"),
offset_var = "pop100000",
time = "date",
unit = "micro_name"
)
# Generate report
select_report(dengue_re, file.path(tempdir(), "random_effects.html"))
## End(Not run)
Merge GHRmodels
Description
This function stack together two or more objects GHRmodels object,
returning one GHRmodels object that contains all the input models.
All models included in the stack must have the same family, outcome, and
data. If any model_id is duplicated across the inputs the new_name
argument must be provided to ensure unique IDs.
Usage
stack_models(..., new_name = NULL, vs_first = FALSE)
Arguments
... |
Two or more |
new_name |
|
vs_first |
Logical. If TRUE columns comparing the model vs the first
model are kept in the |
Details
Combine (Stack) Multiple GHRmodels Objects
Value
A single GHRmodels object containing all models from the inputs.
See Also
subset_models for subsetting GHRmodels objects,
fit_models for fitting INLA models.
Examples
data(dengue_MS)
dengue_MS <- dengue_MS[dengue_MS$year %in% 2010:2012, ]
# Formulas
formulas1 <- "dengue_cases ~ tmin + f(month, model='rw2')"
formulas2 <- "dengue_cases ~ tmax + f(month, model='rw2')"
# Fit
fitmod1 <- fit_models(
formulas = formulas1,
data = dengue_MS,
family = "nbinomial",
offset_var = "pop100000"
)
fitmod2 <- fit_models(
formulas = formulas2,
data = dengue_MS,
family = "nbinomial",
offset_var = "pop100000"
)
# Stack
stacked <- stack_models(fitmod1, fitmod2, new_name = "mod")
Subset GHRmodels Objects
Description
This function subsets selected models from a GHRmodels object into a new
reduced GHRmodels object.
Usage
subset_models(models, mod_id, new_name = NULL)
Arguments
models |
A |
mod_id |
A character vector of model IDs indicating which model(s)
to keep. These must match |
new_name |
|
Value
A new GHRmodels object containing only the specified model(s).
See Also
stack_models for combining GHRmodels objects,
fit_models for fitting INLA models.
Examples
# Load example dataset
data(dengue_MS)
dengue_MS <- dengue_MS[dengue_MS$year %in% 2010:2012, ]
# Formulas
formulas <- c(
"dengue_cases ~ tmin + f(month, model='rw2')",
"dengue_cases ~ pdsi + f(month, model='rw2')"
)
# Fit
fitmod <- fit_models(
formulas = formulas,
data = dengue_MS,
family = "nbinomial",
offset_var = "pop100000"
)
# Subset a single model
sub1 <- subset_models(fitmod, mod_id = "mod1")
Generate INLA-compatible Model Formulas
Description
This function streamlines the creation of INLA-compatible model formulas by automatically structuring fixed effects, random effects, and interactions. It accepts a list of covariate sets and produces a corresponding set of model formulas that share a common random effect structure.
Usage
write_inla_formulas(
outcome,
covariates = NULL,
baseline = TRUE,
re1 = list(id = NULL, model = NULL, replicate = NULL, group = NULL, graph = NULL,
cyclic = FALSE, scale.model = FALSE, constr = FALSE, adjust.for.con.comp = FALSE,
hyper = NULL),
re2 = NULL,
re3 = NULL,
re4 = NULL,
re5 = NULL
)
Arguments
outcome |
Character string specifying the name of the outcome variable. |
covariates |
A list of character vectors, where each vector contains covariate names to be included in the model. If a single vector is provided, a single model formula is generated. |
baseline |
Logical; If |
re1 |
A list defining a random effect structure. Up to five such
lists ( |
re2 |
Additional random effect definitions, as described for |
re3 |
Additional random effect definitions, as described for |
re4 |
Additional random effect definitions, as described for |
re5 |
Additional random effect definitions, as described for |
Details
The write_inla_formulas() function simplifies the creation of multiple
INLA models by automatically structuring fixed effects, random effects,
and interactions. The function ensures that all models have a consistent
structure, making them easier to analyze and modify.
If baseline = TRUE, a null formula (without covariates) is included as
the first element of the list.
The number of formulas generated depends on the length of the
covariates list.
Random effects can be added using re1, ..., re5, where each effect
must be a named list
(e.g. re1 = list(id = "year_id", model = "rw1")).
In the list the following fields are strictly necessary:
-
id(character): the variable name that indexes the random effect (e.g., "year", "region"). -
model(character): the type of random effect. Supported values include:"iid","rw1","rw2","bym", and"bym2". The following optional fields can be provided in the random effect list:
-
replicate(character): defines an additional variable used to replicate the random effect structure across groups (e.g., spatial units for repeated time-series). -
group(character): used to model group-specific effects or nested structures. -
graph(character): required for"bym"and"bym2"models; refers to the name of an object in the environment that holds the spatial adjacency matrix. -
cyclic(logical): indicates whether the random walk ("rw1"or"rw2") is cyclic. Default isFALSE. Use for periodic structures (e.g., months). -
scale.model(logical): ifTRUE, scales structured random effects (likerw1,rw2,bym) so the generalized variance is 1. Forbym2INLA automatically appliesscale.model = TRUEinternally. -
constr(logical): IfTRUE, a sum to zero constrain is introduced. This 'constr' option is applied only to 'iid' random effects. Forrw,ar,bym,bym2INLA automatically appliesscale.model = TRUEinternally. -
adjust.for.con.comp(logical): ifTRUE, accounts for disconnected components in spatial graphs. Recommended for"bym"and"bym2". Default isFALSE. -
hyper(character): the name of an object in the environment that contains the hyperprior specification for the random effect's precision or other parameters.
-
For more information on random effects in R-INLA, see Bayesian inference with INLA: Mixed-effects Models.
Value
A character vector of INLA model formulas.
See Also
as_GHRformulas for transforming model formulas into
structured objects.
Examples
# Define covariates of interest
covs <- c("tmin.l1", "tmin.l2", "pdsi.l1", "pdsi.l2", "urban_level")
# Combine covariate names using a pattern-matching functionality
combined_covariates <- cov_multi(
covariates = covs,
pattern = c("tmin", "pdsi", "urban_level")
)
# Define hyperprior specifications for random effects
prior_re1 <- list(prec = list(prior = "loggamma", param = c(0.01, 0.01)))
prior_re2 <- list(prec = list(prior = "loggamma", param = c(0.01, 0.01)))
prior_re3 <- list(
prec = list(prior = "pc.prec", param = c(0.5 / 0.31, 0.01)),
phi = list(prior = "pc", param = c(0.5, 2 / 3))
)
# Write a set of INLA-compatible model formulas
inla_formulas <- write_inla_formulas(
outcome = "dengue_cases",
covariates = combined_covariates,
re1 = list(
id = "month_id",
model = "rw1",
cyclic = TRUE,
hyper = "prior_re1",
replicate = "spat_meso_id"
),
re2 = list(
id = "year_id",
model = "rw1",
hyper = "prior_re2"
),
re3 = list(
id = "spat_id",
model = "iid",
hyper = "prior_re3"
),
baseline = TRUE
)