R/adapter-survival.R

Defines functions pm_surv_special_vars pm_surv_groups pm_scale_name.survreg pm_scale_name.coxph pm_scale_name.pm_foreign pm_scale_name.default pm_scale_name pm_df_rule_z pm_df_rule.survreg pm_linkinv.survreg pm_basis.survreg pm_vcov.survreg pm_df_rule.coxme pm_linkinv.coxme pm_contrasts.coxme pm_basis.coxme pm_vcov.coxme pm_coef.coxme pm_df_rule.coxph pm_linkinv.coxph pm_basis.coxph pm_surv_centre pm_surv_supported pm_surv_frailty_rows pm_surv_basis pm_fixed_terms.coxph

## Native adapters for survival models (dev/review-classes-2.md, Step C2): survival::coxph (with strata(),
## cluster = and frailty() terms), coxme::coxme and survival::survreg. Wald z tests (likelihood fits, no residual
## variance), as SAS PROC PHREG and LIFEREG. Checked against SAS (dev/sas/survival.sas, test-survival.R).
##
## What the numbers are (pm_scale_name(), used by pm_back_label()):
##   coxph, coxme  the means are log hazards relative to the average linear predictor of the data (no intercept;
##                 pm_surv_basis() centres the design); their differences are log hazard ratios. Back-transformed:
##                 hazards relative to that average; with a frailty or random effect, for a typical cluster.
##   survreg       the means are on the log-time scale; back-transformed (exp) they are the median survival time
##                 (lognormal, loglogistic), the mean survival time (exponential) or the characteristic time at which
##                 63% have had the event (Weibull); differences are log time ratios.

## The fixed-effect terms of a Cox model: strata(), frailty(), cluster(), tt(), ridge() and pspline() terms left out
#' @exportS3Method NULL
pm_fixed_terms.coxph <- function(model) {
  tt <- stats::terms(model)
  fac <- attr(tt, "factors")
  sp <- c(unlist(attr(tt, "specials")), pm_surv_frailty_rows(tt))
  if (!length(sp) || !length(fac)) return(tt)
  drop <- which(colSums(fac[sp, , drop = FALSE]) > 0)
  if (!length(drop)) return(tt)
  if (length(drop) == ncol(fac)) stop("The Cox model has no fixed effects besides strata or frailty terms.", call. = FALSE)
  stats::drop.terms(tt, drop, keep.response = TRUE)
}
#' @exportS3Method NULL
pm_fixed_terms.survreg <- pm_fixed_terms.coxph

## The design of a Cox model has no intercept (it is absorbed in the baseline hazard), so a mean needs a reference.
## The rows are centred at the column means of the fit's design: a mean is then the log hazard relative to the
## average linear predictor of the data, the same whatever the coding of the factors (contrasts) and never 0 by
## construction. Differences (log hazard ratios) do not depend on the centre.
pm_surv_basis <- function(model, newdata, contrasts = NULL, xlev = NULL) {
  tt <- stats::delete.response(pm_fixed_terms(model))
  X <- pm_basis.default(model, newdata, terms = tt, contrasts = contrasts, xlev = xlev)
  X <- X[, colnames(X) != "(Intercept)", drop = FALSE]
  pm_surv_supported(model, colnames(X))
  ctr <- pm_surv_centre(model)
  k <- intersect(colnames(X), names(ctr))
  X[, k] <- sweep(X[, k, drop = FALSE], 2, ctr[k])
  X
}

## Rows of the terms' factors that are frailty terms coxph knows by function rather than as a special
## (frailty.gaussian(), frailty.t(), frailty.gamma())
pm_surv_frailty_rows <- function(tt) {
  v <- vapply(as.list(attr(tt, "variables"))[-1], function(e) paste(deparse(e), collapse = ""), "")
  which(grepl("^frailty\\.[a-z]+\\(", v))
}

## Coefficients that are not fixed effects of the formula (tt(), pspline(), ridge(), an interaction with strata(),
## frailty(sparse = FALSE)): no mean can be built from them, so stop and name them
pm_surv_supported <- function(model, cols) {
  b <- pm_coef(model)
  miss <- setdiff(names(b)[!is.na(b)], cols)
  if (length(miss)) {
    stop("predictmeans handles Cox and survreg models with fixed effects, strata(), cluster and sparse frailty ",
         "terms; the coefficients ", paste(utils::head(miss, 4), collapse = ", "), if (length(miss) > 4) ", ...",
         " come from a term it cannot build means from (tt(), pspline(), ridge(), an interaction with strata() ",
         "or frailty(sparse = FALSE)). Refit without it, or with the covariate as an ordinary term.", call. = FALSE)
  }
  invisible(TRUE)
}

## Column means of the design of a Cox fit (coxph sets them to 0 for 0/1 columns in $means, so they are taken from
## the model matrix; coxme keeps the true ones)
pm_surv_centre <- function(model) {
  if (inherits(model, "coxme")) return(stats::setNames(model$means, names(coxme::fixef(model))))
  X <- tryCatch(stats::model.matrix(model), error = function(e) NULL)
  if (is.null(X)) return(NULL)
  w <- model$weights
  if (is.null(w) || length(w) != nrow(X)) w <- rep(1, nrow(X))
  colSums(X * w) / sum(w)
}

#' @exportS3Method pm_basis coxph
pm_basis.coxph <- function(model, newdata, contrasts = NULL, xlev = NULL, ...) {
  pm_surv_basis(model, newdata, contrasts, xlev)
}
#' @exportS3Method pm_linkinv coxph
pm_linkinv.coxph <- function(model, ...) exp
#' @exportS3Method NULL
pm_df_rule.coxph <- function(model, df_method, kr_info) pm_df_rule_z(model, df_method)

#' @exportS3Method pm_coef coxme
pm_coef.coxme <- function(model, ...) coxme::fixef(model)
#' @exportS3Method pm_vcov coxme
pm_vcov.coxme <- function(model, ...) {
  V <- as.matrix(stats::vcov(model))
  dimnames(V) <- list(names(coxme::fixef(model)), names(coxme::fixef(model)))
  V
}
#' @exportS3Method pm_basis coxme
pm_basis.coxme <- function(model, newdata, contrasts = NULL, xlev = NULL, ...) {
  pm_surv_basis(model, newdata, contrasts, xlev)
}
#' @exportS3Method pm_contrasts coxme
pm_contrasts.coxme <- function(model, ...) model$contrasts
#' @exportS3Method pm_linkinv coxme
pm_linkinv.coxme <- function(model, ...) exp
#' @exportS3Method NULL
pm_df_rule.coxme <- function(model, df_method, kr_info) pm_df_rule_z(model, df_method)

#' @exportS3Method pm_vcov survreg
pm_vcov.survreg <- function(model, ...) {
  b <- stats::coef(model)
  V <- as.matrix(stats::vcov(model))
  keep <- names(b)[!is.na(b)]
  V[keep, keep, drop = FALSE]                        # (without the Log(scale) row)
}
#' @exportS3Method pm_basis survreg
pm_basis.survreg <- function(model, newdata, contrasts = NULL, xlev = NULL, ...) {
  tt <- stats::delete.response(pm_fixed_terms(model))
  X <- pm_basis.default(model, newdata, terms = tt, contrasts = contrasts, xlev = xlev)
  pm_surv_supported(model, colnames(X))
  X
}
#' @exportS3Method pm_linkinv survreg
pm_linkinv.survreg <- function(model, ...) {
  d <- survival::survreg.distributions[[model$dist]]
  if (!is.null(d$trans) && isTRUE(all.equal(d$trans(c(1, 2)), log(c(1, 2))))) exp
}
#' @exportS3Method NULL
pm_df_rule.survreg <- function(model, df_method, kr_info) pm_df_rule_z(model, df_method)

## Likelihood fits without a residual variance: Wald z tests; another df_method does not apply
pm_df_rule_z <- function(model, df_method) {
  if (df_method != "auto") {
    warning("'df_method = \"", df_method, "\"' does not apply to ", class(model)[1], " models (Wald z tests); ignored.",
            call. = FALSE)
  }
  list(df_type = "asymptotic", vcov_adj = NULL)
}

## What the back-transformed values of a class are (pm_back_label()), or NULL for the general rule
pm_scale_name <- function(model) UseMethod("pm_scale_name")
#' @exportS3Method NULL
pm_scale_name.default <- function(model) NULL
#' @exportS3Method NULL
pm_scale_name.pm_foreign <- function(model) attr(model, "pm_foreign")$scale_label
#' @exportS3Method NULL
pm_scale_name.coxph <- function(model) {
  paste0("hazard relative to the data's average linear predictor",
         if (length(pm_surv_groups(model))) paste0(", for a typical ", paste(pm_surv_groups(model), collapse = " and ")))
}
#' @exportS3Method NULL
pm_scale_name.coxme <- pm_scale_name.coxph
#' @exportS3Method NULL
pm_scale_name.survreg <- function(model) {
  switch(model$dist,
         lognormal = , loglogistic = "median survival time",
         exponential = "mean survival time",
         weibull = "characteristic survival time (63% have had the event; exp of the location)",
         if (!is.null(pm_linkinv.survreg(model))) "exp of the location (time scale)")
}

## Grouping factors of a frailty or random effect, whose effect the hazards are conditional on
pm_surv_groups <- function(model) {
  if (inherits(model, "coxme")) return(names(coxme::VarCorr(model)))
  pm_surv_special_vars(model, "frailty")
}

## The variables inside the strata() or frailty() terms of a coxph/survreg formula
pm_surv_special_vars <- function(model, special = c("strata", "frailty", "cluster")) {
  special <- match.arg(special)
  tt <- stats::terms(model)
  i <- c(attr(tt, "specials")[[special]], if (special == "frailty") pm_surv_frailty_rows(tt))
  unique(unlist(lapply(i, function(k) all.vars(attr(tt, "variables")[[k + 1]]))))
}

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.