R/foreign.R

Defines functions pm_fb_label pm_linkinv.pm_foreign pm_df.pm_foreign pm_basis.pm_foreign pm_vcov.pm_foreign pm_coef.pm_foreign pm_fb_quiet_contrasts pm_fb_marginaleffects pm_fb_scale_label pm_fb_emmeans pm_fb_default_ok pm_fb_has_emmeans pm_fb_user_adapter pm_fb_has_method pm_fb_source pm_foreign

## Model classes predictmeans has no adapter for (dev/review-classes-2.md, Step B).
##
## pm_means_model() (R/adapter.R) passes every model through pm_foreign(). The
## source of the linear basis is chosen here, once (pm_fb_source()):
##   "native"           a class predictmeans models itself (pm_native_classes), or one with the user's own
##                      adapter methods (?pm_coef): returned as it is;
##   "emmeans"          emmeans has a basis for the class (emm_basis()): its design rows for predictmeans' grid,
##                      coefficients, covariance, df of each row and link. A basis that is not linear in fixed
##                      coefficients (emmeans' response-scale "pseudo" bases) or comes from posterior draws stops;
##   "default"          coef() and vcov() agree: the default methods, as before;
##   "marginaleffects"  marginaleffects can set the coefficients and predict on the link scale: the basis is the
##                      Jacobian of those predictions, used only when they are exactly linear in the coefficients
##                      (checked on every grid); df as for any other class (df.residual(), else normal).
## A wrapped model keeps its class, with "pm_foreign" appended (so the adapter methods below are found first and
## every other method of the class still works) and the parts in attr(model, "pm_foreign").

## Classes with their own methods in predictmeans (any class that inherits one is native too)
pm_native_classes <- c("lm", "gls", "lme", "merMod", "glmmTMB", "gam", "semireg", "aovlist", "polr", "clm", "clmm",
                       "vglm", "multinom", "pm_catfit", "pm_lm_reml", "mmrm", "betareg", "coxph", "coxme", "survreg",
                       "pm_bayesfit")
pm_adapter_generics <- c("pm_coef", "pm_vcov", "pm_basis", "pm_df", "pm_linkinv", "pm_contrasts", "pm_data")
## emmeans' arguments for classes whose default basis is not the linear predictor of the mean
pm_fb_emm_args <- list(betareg = list(mode = "link"))

pm_foreign <- function(model, source = pm_fb_source(model)) {
  if (inherits(model, "pm_foreign") || source %in% c("native", "default")) return(model)
  fb <- if (source == "emmeans") pm_fb_emmeans(model) else pm_fb_marginaleffects(model)
  fb$source <- source
  fb$class <- class(model)[1]
  attr(model, "pm_foreign") <- fb
  # appended, so every other method of the class still works; first only when a source is forced on a class
  # with its own adapter (a check of the fallback against the native code)
  native <- inherits(model, pm_native_classes) || pm_fb_user_adapter(model)
  if (native && isS4(model)) stop("The fallback cannot be forced on an S4 class ('", class(model)[1], "').", call. = FALSE)
  class(model) <- if (native) c("pm_foreign", class(model)) else c(class(model), "pm_foreign")
  model
}

pm_fb_source <- function(model) {
  if (inherits(model, "pm_foreign")) return(attr(model, "pm_foreign")$source)
  if (inherits(model, pm_native_classes) || pm_fb_user_adapter(model)) return("native")
  if (isS4(model)) {                       # (no class can be appended: the default methods, as before, or stop)
    if (pm_fb_default_ok(model)) return("default")
    stop("Class '", class(model)[1], "' is an S4 class without working coef() and vcov(): write pm_coef(), ",
         "pm_vcov() and pm_basis() methods for it (see ?pm_coef).", call. = FALSE)
  }
  if (pm_fb_has_emmeans(model)) return("emmeans")
  if (pm_fb_default_ok(model)) return("default")
  if (requireNamespace("marginaleffects", quietly = TRUE) && requireNamespace("insight", quietly = TRUE)) {
    return("marginaleffects")
  }
  stop("Class '", class(model)[1], "' is not handled: install emmeans or marginaleffects (they may support it), ",
       "or write pm_coef(), pm_vcov() and pm_basis() methods for it (see ?pm_coef).", call. = FALSE)
}

pm_fb_has_method <- function(generic, model) {
  any(vapply(setdiff(class(model), c("default", "pm_foreign")),
             function(cl) !is.null(utils::getS3method(generic, cl, optional = TRUE)), logical(1)))
}
pm_fb_user_adapter <- function(model) any(vapply(pm_adapter_generics, pm_fb_has_method, logical(1), model = model))
## (found as emmeans finds them: a method in any loaded namespace, registered or not, e.g. emmeans' own for
## betareg and mmrm's for mmrm)
pm_fb_has_emmeans <- function(model) {
  requireNamespace("emmeans", quietly = TRUE) &&
    any(vapply(setdiff(class(model), c("default", "pm_foreign")),
               function(cl) !is.null(utils::getS3method("emm_basis", cl, optional = TRUE, envir = asNamespace("emmeans"))) ||
                 length(utils::getAnywhere(paste0("emm_basis.", cl))$objs) > 0, logical(1)))
}

## The default methods agree: named coefficients and a covariance of their size (Kmatrix() then checks that the
## coefficients are columns of the design, as before)
pm_fb_default_ok <- function(model) {
  isTRUE(tryCatch({
    b <- stats::coef(model)
    V <- as.matrix(stats::vcov(model))
    # (as pm_model_parm(): vcov() of lm keeps the aliased ones, as NA)
    is.numeric(b) && !is.null(names(b)) && (all(dim(V) == length(b)) || all(dim(V) == sum(!is.na(b))))
  }, error = function(e) FALSE))
}

## Level 2: emmeans' basis. emm_basis() gives the design rows for any grid, so predictmeans keeps its own grid,
## weights and empty-cell rules; the factor levels are those of the fit (predictmeans' xlev first). emmeans' df
## functions take the estimable columns only, as emmeans calls them; a matrix gives the df of a joint test.
pm_fb_emmeans <- function(model) {
  cls <- class(model)[1]
  fail <- function(e) if (grepl("^For class", conditionMessage(e))) stop(e) else stop("Class '", cls, "' could not be handled through emmeans (", conditionMessage(e), "): write ",
                           "pm_coef(), pm_vcov() and pm_basis() methods for it (see ?pm_coef).", call. = FALSE)
  rd <- tryCatch(emmeans::recover_data(model), error = fail)
  if (!is.data.frame(rd)) fail(simpleError(paste(rd, collapse = " ")))
  trms <- attr(rd, "terms")
  misc <- attr(rd, "misc")
  cl <- intersect(class(model), names(pm_fb_emm_args))
  args <- if (length(cl)) pm_fb_emm_args[[cl[1]]] else list()
  mf <- stats::model.frame(trms, rd, na.action = stats::na.omit)
  is_lev <- vapply(mf, function(z) is.factor(z) || is.character(z), logical(1))
  xlev0 <- lapply(mf[is_lev], function(z) if (is.factor(z)) levels(z) else sort(unique(z)))
  emm <- function(grid, xlev = NULL) {
    xl <- c(xlev, xlev0[setdiff(names(xlev0), names(xlev))])
    b <- pm_fb_quiet_contrasts(do.call(emmeans::emm_basis, c(list(model, trms, xl, grid, misc = misc, options = list()),
                                                              args)))
    if (NROW(b$X) != nrow(grid)) {
      stop("For class '", cls, "', emmeans' basis has ", NROW(b$X), " rows for ", nrow(grid), " grid rows (a ",
           "multivariate fit, e.g. several quantiles or responses): fit one model per response.", call. = FALSE)
    }
    b
  }
  b <- tryCatch(emm(rd), error = fail)
  p <- length(b$bhat)
  if (length(b$post.beta) && !all(is.na(b$post.beta))) {
    stop("Class '", cls, "' is a Bayesian fit: its means come from posterior draws; use emmeans for it.", call. = FALSE)
  }
  b1 <- emm(rd[1, , drop = FALSE])
  if (ncol(b$X) != p || ncol(b1$X) != p || !identical(b1$bhat, b$bhat)) {
    stop("For class '", cls, "', emmeans gives a basis that is not linear in the model's coefficients ",
         "(response-scale means by the delta method): predictmeans cannot use it. Use emmeans for this class, or ",
         "write pm_coef(), pm_vcov() and pm_basis() methods (see ?pm_coef).", call. = FALSE)
  }
  nm <- colnames(b$X)
  if (is.null(nm) || anyNA(nm) || anyDuplicated(nm)) nm <- if (!is.null(names(b$bhat))) names(b$bhat) else paste0("b", seq_len(p))
  bhat <- stats::setNames(as.numeric(b$bhat), nm)
  est <- !is.na(bhat)
  V <- as.matrix(b$V)
  if (!all(dim(V) == sum(est))) {
    stop("emmeans gives a covariance that does not match the coefficients of class '", cls, "'.", call. = FALSE)
  }
  dimnames(V) <- list(nm[est], nm[est])
  # rows of L in the estimable columns (pm_inference()) or in all columns (emmeans' design rows)
  on_est <- function(L) { L <- rbind(L); if (ncol(L) == p) L[, est, drop = FALSE] else L }
  df_row <- function(k) if (all(k == 0)) Inf else as.numeric(b$dffun(k, b$dfargs))
  df <- function(L) { L <- on_est(L); vapply(seq_len(nrow(L)), function(i) df_row(L[i, ]), numeric(1)) }
  df_joint <- function(L) {
    L <- on_est(L)
    if (nrow(L) == 1) return(df_row(L[1, ]))
    d <- tryCatch(as.numeric(b$dffun(L, b$dfargs)), error = function(e) NULL)
    if (length(d) == 1 && !is.na(d) && d > 0) d
  }
  # how the df are made, for settings$df_method: from three rows (a mean, another, their difference)
  Xe <- b$X[, est, drop = FALSE]
  d3 <- c(df_row(Xe[1, ]), df_row(Xe[nrow(Xe), ]), df_row(Xe[1, ] - Xe[nrow(Xe), ]))
  mmrm_method <- if (inherits(model, "mmrm")) tryCatch(mmrm::component(model, "method"), error = function(e) NULL)
  df_label <- if (all(d3 == Inf)) {
    "asymptotic (z)"
  } else if (is.character(mmrm_method)) {
    paste0(mmrm_method, " (mmrm, through emmeans)")
  } else if (isTRUE(all(d3 == d3[1]))) {
    "emmeans (one df for all rows)"
  } else {
    "emmeans (per row)"
  }
  tran <- b$misc$tran
  linkinv <- if (is.list(tran) && is.function(tran$linkinv)) {
    tran$linkinv
  } else if (is.character(tran)) {
    f <- tryCatch(stats::make.link(tran)$linkinv, error = function(e) NULL)
    if (is.null(f) && requireNamespace("insight", quietly = TRUE)) f <- tryCatch(insight::link_inverse(model), error = function(e) NULL)
    if (is.function(f)) f
  }
  list(coef = bhat, vcov = V,
       basis = function(newdata, xlev = NULL) {
         X <- emm(newdata, xlev)$X
         if (ncol(X) != p) stop("emmeans' basis for these rows has ", ncol(X), " columns, not ", p, ".", call. = FALSE)
         colnames(X) <- nm
         X
       },
       df = df, df_joint = df_joint, df_label = df_label,
       linkinv = linkinv, link_unknown = if (is.null(linkinv) && is.character(tran)) tran,
       scale_label = pm_fb_scale_label(if (is.character(b$misc$inv.lbl) && b$misc$inv.lbl != "response") b$misc$inv.lbl, nm),
       offset = !is.null(attr(trms, "offset")) || !is.null(stats::getCall(model)$offset),
       mode = args$mode)
}

## What the back-transformed values of a class without an adapter are: emmeans' name of the scale (e.g. "hazard"),
## else the inverse link of the class's linear predictor; without an intercept, relative to the baseline
pm_fb_scale_label <- function(inv_lbl, coef_names) {
  lab <- if (is.null(inv_lbl)) "inverse link of the linear predictor (the class's own quantity, not always a mean)" else inv_lbl
  if (!"(Intercept)" %in% coef_names) lab <- paste(lab, "relative to the baseline (covariates at 0, first levels)")
  lab
}

## Level 3: the exact Jacobian of marginaleffects' link-scale predictions. A linear predictor is checked on every
## grid: the second differences vanish and the predictions equal X b (no offset).
pm_fb_marginaleffects <- function(model) {
  b <- tryCatch(marginaleffects::get_coef(model), error = function(e) NULL)
  V <- tryCatch(as.matrix(marginaleffects::get_vcov(model)), error = function(e) NULL)
  if (!is.numeric(b) || is.null(names(b)) || anyNA(b) || !is.numeric(V) || !all(names(b) %in% rownames(V))) {
    stop("marginaleffects gives no coefficients and covariance that match for class '", class(model)[1],
         "': write pm_coef(), pm_vcov() and pm_basis() methods for it (see ?pm_coef).", call. = FALSE)
  }
  V <- V[names(b), names(b), drop = FALSE]
  pred <- function(bb, nd) {
    tryCatch(as.numeric(marginaleffects::get_predict(marginaleffects::set_coef(model, bb), newdata = nd,
                                                     type = "link")$estimate),
             error = function(e) stop("marginaleffects cannot predict class '", class(model)[1], "' on the link ",
                                      "scale (", conditionMessage(e), "): write pm_coef(), pm_vcov() and pm_basis() ",
                                      "methods for it (see ?pm_coef).", call. = FALSE))
  }
  basis <- function(newdata, xlev = NULL) {
    p0 <- pm_fb_quiet_contrasts(pred(b, newdata))
    h <- 1e-3 * pmax(1, abs(b))
    up <- dn <- matrix(0, length(p0), length(b))
    for (j in seq_along(b)) {
      e <- replace(numeric(length(b)), j, h[j])
      up[, j] <- pm_fb_quiet_contrasts(pred(b + e, newdata))
      dn[, j] <- pm_fb_quiet_contrasts(pred(b - e, newdata))
    }
    X <- sweep(up - dn, 2, 2 * h, "/")
    tol <- 1e-8 * max(1, abs(p0))
    if (any(abs(up + dn - 2 * p0) > tol) || any(abs(p0 - drop(X %*% b)) > tol)) {
      stop("For class '", class(model)[1], "', marginaleffects' link-scale predictions are not a linear function of ",
           "the coefficients (or hold an offset): predictmeans cannot use them. Write pm_coef(), pm_vcov() and ",
           "pm_basis() methods for this class (see ?pm_coef).", call. = FALSE)
    }
    dimnames(X) <- list(NULL, names(b))
    X
  }
  linkinv <- tryCatch(insight::link_inverse(model), error = function(e) NULL)
  list(coef = b, vcov = V, basis = basis, df = NULL, linkinv = if (is.function(linkinv)) linkinv,
       scale_label = pm_fb_scale_label(NULL, names(b)), offset = FALSE)
}

## (model.frame() warns "contrasts dropped from factor" when a data column carries contrasts the formula does not use)
pm_fb_quiet_contrasts <- function(expr) {
  withCallingHandlers(expr, warning = function(w) {
    if (grepl("contrasts dropped from factor", conditionMessage(w))) invokeRestart("muffleWarning")
  })
}

#' @exportS3Method pm_coef pm_foreign
pm_coef.pm_foreign <- function(model, ...) attr(model, "pm_foreign")$coef
#' @exportS3Method pm_vcov pm_foreign
pm_vcov.pm_foreign <- function(model, ...) attr(model, "pm_foreign")$vcov
#' @exportS3Method pm_basis pm_foreign
pm_basis.pm_foreign <- function(model, newdata, xlev = NULL, ...) attr(model, "pm_foreign")$basis(newdata, xlev)
## (joint = TRUE: one df for the joint F test of the rows of L, or NULL; pm_inference() then takes the smallest)
#' @exportS3Method pm_df pm_foreign
pm_df.pm_foreign <- function(model, L, joint = FALSE, ...) {
  fb <- attr(model, "pm_foreign")
  if (is.null(fb$df)) return(NULL)
  if (joint) return(fb$df_joint(L))
  structure(fb$df(L), label = fb$df_label)
}
#' @exportS3Method pm_linkinv pm_foreign
pm_linkinv.pm_foreign <- function(model, ...) attr(model, "pm_foreign")$linkinv

## The source of the basis, for settings$source: "model" (native or default methods), "emmeans", "marginaleffects"
pm_fb_label <- function(model) if (inherits(model, "pm_foreign")) attr(model, "pm_foreign")$source else "model"

Try the predictmeans package in your browser

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

predictmeans documentation built on Dec. 3, 2026, 5:07 p.m.