rtmb_glmer: RTMB-based GLMM wrapper function

View source: R/wrapper_glmer.R

rtmb_glmerR Documentation

RTMB-based GLMM wrapper function

Description

RTMB-based GLMM wrapper function

Usage

rtmb_glmer(
  formula,
  data = NULL,
  family = "gaussian",
  laplace = FALSE,
  prior = prior_flat(),
  y_range = NULL,
  init = NULL,
  fixed = NULL,
  gmc = NULL,
  centering = NULL,
  cwc = NULL,
  std = FALSE,
  view = NULL,
  within = NULL,
  factors = NULL,
  contrasts = "treatment",
  sigma_by = NULL,
  resid_corr = NULL,
  resid_time = NULL,
  resid_group = NULL,
  generate = NULL,
  missing = c("listwise", "fiml"),
  WAIC = FALSE,
  .force_sum = FALSE
)

Arguments

formula

lme4-style formula (e.g., Y ~ X + (1 | GID))

data

Optional data frame. If omitted, variables are resolved from the formula environment. In this mode, use bare variable names; formulas using $, [[, or . require an explicit data argument.

family

Character string of the distribution family (e.g., "gaussian", "binomial", "poisson", "ordered", "sequential")

laplace

Logical; whether to marginalize random effects using Laplace approximation

prior

An object of class "rtmb_prior" specifying the prior distribution. Use 'prior_flat()', 'prior_normal()', 'prior_weak()', 'prior_rhs()', or 'prior_ssp()'. 'prior_jzs()' is available for continuous families. Default is 'prior_flat()'.

y_range

Theoretical minimum and maximum values of the response variable as a vector c(min, max). Required when using weakly informative or regularized priors with continuous models.

init

List of initial values (generated automatically based on glm if omitted)

fixed

Optional named list of fixed values for specific parameters.

gmc

Character vector of variable names for Grand Mean Centering (GMC). If "all", all numeric variables are centered.

centering

Alias for 'gmc'.

cwc

List for Centering Within Cluster (CWC). Should contain cluster (group variable) and pars (variable names to center). You can also use cwc = list(ID, "x") or cwc = list(ID, "all"); "all" centers all numeric fixed-effect variables within the cluster.

std

Logical; if 'TRUE', add post-hoc standardized fixed-effect coefficients as 'b_std'. Every column of the fixed-effect design matrix is standardized, including columns generated from factors and interactions. For Gaussian models, coefficients are scaled by both the predictor and response standard deviations. For other families, only the predictor standard deviations are used, so coefficients remain on the link scale.

view

Character vector of parameter names to prioritize in summary.

within

Optional list for wide-to-long conversion.

factors

Character vector of variable names to be treated as factors.

contrasts

Character string specifying the contrast type ("treatment" or "sum").

sigma_by

Character vector specifying variables to group residual variance by (heteroscedasticity).

resid_corr

Residual correlation structure: "ar1" (Autoregressive), "cs" (Compound Symmetry), "toep" (Toeplitz), or "un" (Unstructured).

resid_time

Variable name for time points in residual correlation.

resid_group

Variable name for grouping in residual correlation.

generate

Optional expression for generated quantities.

missing

Missing value handling strategy: "listwise".

WAIC

Logical; if TRUE, add pointwise 'log_lik' to the generate block for WAIC.

.force_sum

Logical; internal use only.

Examples

  # --- 1. Linear Regression (rtmb_lm) ---
  # Fit a linear regression model using the debate dataset
  data(debate, package = "BayesRTMB")
  fit_lm <- rtmb_lm(sat ~ talk + perf, data = debate)
  map_lm <- fit_lm$optimize()
  map_lm$summary()

  # --- 2. Generalized Linear Model (rtmb_glm) ---
  # Fit a logistic regression model using the debate dataset
  data(debate, package = "BayesRTMB")
  fit_glm <- rtmb_glm(cond ~ talk + sat, data = debate, family = "bernoulli")
  map_glm <- fit_glm$optimize()
  map_glm$summary()

  # --- 3. Generalized Linear Mixed Model (rtmb_glmer) ---
  # Fit a linear mixed-effects model using the debate dataset
  data(debate, package = "BayesRTMB")
  fit_glmer <- rtmb_glmer(talk ~ cond + (1 | group), data = debate, family = "gaussian")

  # MAP estimation using Laplace approximation for random effects
  map_glmer <- fit_glmer$optimize(laplace = TRUE)
  map_glmer$summary()

  # MCMC sampling (chains and iterations reduced for faster execution)
  
  mcmc_glmer <- fit_glmer$sample(sampling = 500, warmup = 500, chains = 2)
  mcmc_glmer$summary()
  

  # --- 4. Linear Mixed Model (rtmb_lmer) ---
  # A convenient wrapper for Gaussian mixed models (identical to rtmb_glmer with family="gaussian")
  fit_lmer <- rtmb_lmer(sat ~ talk + (1 | group), data = debate)
  map_lmer <- fit_lmer$optimize()
  map_lmer$summary()

  # --- 5. Regularized Regression (Variable Selection) ---
  # You can apply regularization to the fixed effects to shrink noise variables towards zero.
  # Use prior = prior_rhs() for the Regularized Horseshoe prior,
  # or prior_ssp() for the Spike-and-Slab prior.
  # Note: When using regularization, you must specify 'y_range' (the theoretical minimum and maximum
  # values of the response variable) to automatically set up the required weakly informative priors.

  # Fit a linear regression using debate predictors with the Horseshoe prior
  fit_rhs <- rtmb_lm(
    sat ~ talk + perf + skill,
    data = debate,
    prior = prior_rhs(),
    y_range = c(1, 5)
  )
  map_rhs <- fit_rhs$optimize()
  # Summarize only the fixed effects (slopes)
  map_rhs$summary("b")

  # Fit a linear regression with the Spike-and-Slab prior
  fit_ssp <- rtmb_lm(
    sat ~ talk + perf + skill,
    data = debate,
    prior = prior_ssp(),
    y_range = c(1, 5)
  )
  map_ssp <- fit_ssp$optimize()
  map_ssp$summary("b")

BayesRTMB documentation built on Nov. 24, 2026, 9:06 a.m.