R/internal-validate_lincombs_against_formula.R

Defines functions validate_lincombs_against_formula

Documented in validate_lincombs_against_formula

#' Validate lincomb terms against an INLA formula
#'
#' Checks that all variable names used in `inla.make.lincomb()` expressions
#' (inside a list of lincombs) are present in the provided INLA model formula.
#'
#' @param lincombs A list of linear combinations (as generated by `generate_apc_lincombs()`).
#' @param formula The INLA model formula object (e.g., from `generate_MAPC_formula()`).
#'
#' @return Invisible TRUE if all terms match. Otherwise, stops with an informative error.
#' @export
validate_lincombs_against_formula <- function(lincombs, formula) {
  if (!inherits(formula, "formula")) stop("Argument 'formula' must be a formula object.")
  if (!is.list(lincombs)) stop("Argument 'lincombs' must be a list.")

  # Extract variable names used inside each inla.make.lincomb call
  lincomb_terms <- unique(unlist(lapply(lincombs, names)))

  # Extract all variable names from the formula
  fmla_terms <- all.vars(formula)

  # Check which lincomb components are not in the formula
  missing_terms <- setdiff(lincomb_terms, fmla_terms)

  if (length(missing_terms) > 0) {
    stop("Mismatch between `lincomb` and `formula`; the following lincomb terms are not found in the model formula:\n",
         paste(missing_terms, collapse = ", "))
  }

  message("All lincomb terms match variables in the model formula.")
  invisible(TRUE)
}

Try the MAPCtools package in your browser

Any scripts or data that you put into this service are public.

MAPCtools documentation built on June 25, 2025, 5:09 p.m.