R/survival.R

Defines functions survreg_note_sentences survreg_log_time apa_performance.survreg apa_parameters.survreg events_text cox_note_sentences apa_performance.coxph apa_parameters.coxph

Documented in apa_parameters.coxph apa_parameters.survreg apa_performance.coxph apa_performance.survreg

# Cox proportional hazards tables ----

#' @details
#' For Cox proportional hazards models (`survival::coxph`), coefficients are
#' log hazard ratios, tested with Wald *z* tests, and their exponentiated
#' values (shown by default) are hazard ratios, labeled *HR*. A hazard ratio
#' above 1 means that the event happens sooner (at a higher rate) as the
#' predictor increases. The model has no intercept. [apa_note()] names the
#' model and gives the number of cases and of events.
#' @references
#' Cox, D. R. (1972). Regression models and life-tables. *Journal of the Royal
#' Statistical Society: Series B (Methodological), 34*(2), 187--202.
#' \doi{10.1111/j.2517-6161.1972.tb00899.x}
#'
#' Harrell, F. E., Califf, R. M., Pryor, D. B., Lee, K. L., & Rosati, R. A.
#' (1982). Evaluating the yield of medical tests. *JAMA, 247*(18),
#' 2543--2546. \doi{10.1001/jama.1982.03320430047030}
#' @export
#' @rdname apa_parameters
#' @examples
#' \donttest{
#' if (requireNamespace("survival", quietly = TRUE) &&
#'     requireNamespace("carData", quietly = TRUE)) {
#'   # Time to rearrest after release from prison
#'   survival::coxph(
#'     survival::Surv(week, arrest) ~ fin + age + prio,
#'     data = carData::Rossi
#'   ) |>
#'     apa_parameters()
#' }
#' }
apa_parameters.coxph <- function(
  fit,
  predictor_parameters = c(
    "Parameter",
    "Coefficient",
    "SE",
    "Exp_Coefficient",
    "z",
    "p"
  ),
  starred = NA,
  bolded = NA,
  column_formats = NULL,
  t_with_df = TRUE,
  exponentiate = TRUE,
  ...
) {
  if (is.null(column_formats)) {
    column_formats <- the$column_formats
  }
  names(predictor_parameters) <- NULL

  d_b <- parameters::model_parameters(fit, ...) |>
    tibble::as_tibble()
  d_b$Parameter <- pretty_parameter_names(fit, d_b$Parameter)

  if (isTRUE(exponentiate)) {
    d_b <- add_exp_columns(d_b, predictor_parameters)
    column_formats <- label_exp_columns(
      column_formats,
      c(header = "*HR*", latex = "$HR$", abbreviation = "hazard ratio")
    )
  }

  # z tests have infinite df, which should not be displayed
  if ("df_error" %in% colnames(d_b) && all(is.infinite(d_b$df_error))) {
    d_b$df_error <- NULL
  }

  format_apa_parameters(
    d_b,
    predictor_parameters = predictor_parameters,
    starred = starred,
    bolded = bolded,
    column_formats = column_formats,
    t_with_df = t_with_df,
    note = list(
      vcov = describe_vcov(list(...)$vcov),
      model_sentences = cox_note_sentences(fit)
    )
  )
}

#' @details
#' For Cox proportional hazards models (`survival::coxph`), `R2` is
#' Nagelkerke's pseudo-*R*^2^ and `Concordance` is the concordance index
#' (Harrell's *C*): the proportion of pairs of cases in which the case with
#' the higher predicted risk had the event sooner. The default metrics are
#' `R2`, `Concordance`, and `AIC`. Nested models are compared with likelihood
#' ratio tests in [apa_performance_comparison()].
#' @export
#' @rdname apa_performance
apa_performance.coxph <- function(
  fit,
  metrics = c("R2", "Concordance", "AIC"),
  column_formats = NULL
) {
  if (is.null(column_formats)) {
    column_formats <- the$column_formats
  }
  names(metrics) <- NULL
  if (any(metrics == "all")) {
    metrics <- c("R2", "Concordance", "AIC", "AICc", "BIC")
  }
  # performance's residual-based metrics (e.g., RMSE) do not apply
  d <- muffle_backtick_warning(
    performance::model_performance(fit, metrics = c("AIC", "AICc", "BIC", "R2"))
  ) |>
    tibble::as_tibble()
  d$Concordance <- unname(fit$concordance[["concordance"]])
  format_performance(d, metrics, column_formats)
}

# Cox model note sentences ----

#' Note sentences for Cox models
#' @keywords internal
#' @noRd
cox_note_sentences <- function(fit) {
  c(
    paste0(
      "Estimates are from a Cox proportional hazards model ",
      cite("coxRegressionModelsLifetables1972"),
      "."
    ),
    n_sentence(fit$n, events_text(fit$nevent))
  )
}

#' ", with 165 events" (or "1 event") for the sample-size sentence
#' @keywords internal
#' @noRd
events_text <- function(events) {
  paste0(", with ", format(events, big.mark = ","), if (events == 1) " event" else " events")
}

# Parametric survival model tables ----

#' @details
#' For parametric survival models (`survival::survreg`), which are
#' accelerated failure time models for distributions of log time (e.g., the
#' default Weibull, exponential, log-normal, and log-logistic), coefficients
#' are changes in log survival time, tested with Wald *z* tests, and their
#' exponentiated values (shown by default) are time ratios, labeled *TR*. A
#' time ratio above 1 means that the event happens later as the predictor
#' increases, the opposite of a hazard ratio above 1. The constant and the
#' log of the scale parameter, `Log(scale)`, are not exponentiated. The scale
#' is tested only for Weibull models, where a scale of 1 is the exponential
#' model. [apa_note()] names the distribution and gives the number of cases
#' and of events.
#' @references
#' Wei, L. J. (1992). The accelerated failure time model: A useful
#' alternative to the Cox regression model in survival analysis. *Statistics
#' in Medicine, 11*(14--15), 1871--1879. \doi{10.1002/sim.4780111409}
#' @export
#' @rdname apa_parameters
apa_parameters.survreg <- function(
  fit,
  predictor_parameters = c(
    "Parameter",
    "Coefficient",
    "SE",
    "Exp_Coefficient",
    "z",
    "p"
  ),
  starred = NA,
  bolded = NA,
  column_formats = NULL,
  t_with_df = TRUE,
  exponentiate = NULL,
  ...
) {
  if (is.null(column_formats)) {
    column_formats <- the$column_formats
  }
  names(predictor_parameters) <- NULL
  log_time <- survreg_log_time(fit)
  if (is.null(exponentiate)) {
    exponentiate <- log_time
  }

  d_b <- parameters::model_parameters(fit, ...) |>
    tibble::as_tibble()
  is_scale <- d_b$Parameter == "Log(scale)"
  is_constant <- d_b$Parameter == "(Intercept)"
  # Format variable names here, so that the scale row keeps its label
  name_formatter <- column_formats$Parameter@formatter
  d_b$Parameter <- name_formatter(pretty_parameter_names(fit, d_b$Parameter))
  d_b$Parameter[is_scale] <- "Log(scale)"
  column_formats$Parameter@formatter <- \(x, ...) x

  # The scale is tested only where a value of 1 means something: for a
  # Weibull model, it is the exponential model
  if (!identical(fit$dist, "weibull")) {
    for (col in intersect(c("z", "p"), colnames(d_b))) {
      d_b[[col]][is_scale] <- NA
    }
  }

  if (isTRUE(exponentiate)) {
    d_b <- add_exp_columns(d_b, predictor_parameters)
    for (col in intersect(c("Exp_Coefficient", "Exp_CI_low", "Exp_CI_high"), colnames(d_b))) {
      d_b[[col]][is_scale | is_constant] <- NA
    }
    column_formats <- label_exp_columns(
      column_formats,
      if (log_time) {
        c(header = "*TR*", latex = "$TR$", abbreviation = "time ratio")
      } else {
        c(header = the$columns$Exp_Coefficient@header, latex = the$columns$Exp_Coefficient@latex)
      }
    )
  }

  # z tests have infinite df, which should not be displayed
  if ("df_error" %in% colnames(d_b) && all(is.infinite(d_b$df_error))) {
    d_b$df_error <- NULL
  }

  format_apa_parameters(
    d_b,
    predictor_parameters = predictor_parameters,
    starred = starred,
    bolded = bolded,
    column_formats = column_formats,
    t_with_df = t_with_df,
    note = list(
      vcov = describe_vcov(list(...)$vcov),
      model_sentences = survreg_note_sentences(fit)
    )
  ) |>
    labels_formatted()
}

#' @details
#' For parametric survival models (`survival::survreg`), `R2` is
#' Nagelkerke's pseudo-*R*^2^ and `Concordance` is the concordance index
#' (Harrell's *C*), as for Cox models. The default metrics are `R2`,
#' `Concordance`, and `AIC`, and nested models are compared with likelihood
#' ratio tests in [apa_performance_comparison()].
#' @export
#' @rdname apa_performance
apa_performance.survreg <- function(
  fit,
  metrics = c("R2", "Concordance", "AIC"),
  column_formats = NULL
) {
  if (is.null(column_formats)) {
    column_formats <- the$column_formats
  }
  names(metrics) <- NULL
  if (any(metrics == "all")) {
    metrics <- c("R2", "Concordance", "AIC", "AICc", "BIC")
  }
  rlang::check_installed("survival", reason = "for the concordance of survival models.")
  d <- muffle_backtick_warning(
    performance::model_performance(fit, metrics = c("AIC", "AICc", "BIC", "R2"))
  ) |>
    tibble::as_tibble()
  d$Concordance <- unname(survival::concordance(fit)$concordance)
  format_performance(d, metrics, column_formats)
}

# Parametric survival model note sentences ----

#' Does a survreg model's distribution model log time?
#' @keywords internal
#' @noRd
survreg_log_time <- function(fit) {
  rlang::check_installed("survival", reason = "for parametric survival models.")
  dist <- survival::survreg.distributions[[fit$dist]]
  !is.null(dist) && !is.null(dist$trans)
}

#' Note sentences for parametric survival models
#' @keywords internal
#' @noRd
survreg_note_sentences <- function(fit) {
  dist_names <- c(
    weibull = "Weibull",
    exponential = "exponential",
    lognormal = "log-normal",
    loglogistic = "log-logistic",
    gaussian = "normal",
    logistic = "logistic",
    rayleigh = "Rayleigh",
    t = "*t*"
  )
  dist <- if (fit$dist %in% names(dist_names)) dist_names[[fit$dist]] else fit$dist
  y <- fit$y
  n <- nrow(y)
  # The last column of a Surv object is the event indicator
  events <- sum(y[, ncol(y)] == 1)
  article <- if (grepl("^[aeiou]", dist)) "an" else "a"
  log_time <- survreg_log_time(fit)
  c(
    paste0(
      "Estimates are from ",
      if (log_time) "an accelerated failure time model " else "a parametric survival model ",
      cite("weiAcceleratedFailureTime1992"),
      " with ",
      article,
      " ",
      dist,
      " distribution."
    ),
    if (log_time) "Coefficients are changes in log survival time.",
    if (identical(fit$dist, "weibull")) "The test of Log(scale) is a test of the exponential model (scale = 1).",
    n_sentence(n, events_text(events))
  )
}

Try the apa7 package in your browser

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

apa7 documentation built on Dec. 1, 2026, 5:06 p.m.