Nothing
#' Survival Curves and Median Survival Times for the Levels of a Term
#'
#' @description
#' For a Cox model (\code{survival::coxph}) or an accelerated failure time model (\code{survival::survreg}), the
#' survival curve S(t) of each level of \code{modelterm} with pointwise confidence limits, and the median survival
#' time with its limits.
#'
#' @details
#' Each curve is that of one covariate pattern: the level of \code{modelterm}, numeric covariates at their means
#' (as \code{\link{predictmeans}}), and the other factors at the levels in \code{at} (by default their first
#' level, with a message). A curve averaged over the levels of another factor would need the covariance between
#' curves; it is not given, so that no limits are approximate. Give the factor in \code{modelterm} to see a curve
#' for each of its levels.
#' \itemize{
#' \item \code{coxph}: \code{survival::survfit()} with that pattern as \code{newdata} (the Breslow or Efron
#' estimate of the baseline hazard of the fit, and its variance); in a stratified model the strata factor is one
#' of the pattern (in \code{modelterm} or \code{at}), and each curve uses the baseline hazard of its stratum.
#' The curves stop (\code{NA}) after the last follow-up time of the data (of the stratum). The median and its
#' limits are those of \code{quantile()} of the curve.
#' \item \code{survreg}: S(t) = 1 - F((log t - eta) / sigma) for the fitted distribution, with the delta method
#' over the coefficients and log(sigma); the median is exp(eta + sigma q50). Distributions on the log-time
#' scale only, and one scale (no \code{strata()}).
#' }
#' The limits are on the log survival scale (\code{conf.type = "log"}, as \code{survfit()}'s default), at
#' \code{conf_level}; they are pointwise, not a band for the whole curve.
#' @param model A \code{coxph} or \code{survreg} fit, or a \code{brmsfit} of a survival family.
#' @param modelterm A factor of the model, or an interaction of factors (\code{"A:B"}), whose levels get a curve.
#' @param at A named list: levels of the other factors (one each), or values of numeric covariates.
#' @param times The times at which to give S(t). Default: \code{coxph}, every time of the data (events and
#' censorings) up to the last; \code{survreg}, 101 points from 0 to the largest time.
#' @param conf_level The confidence level of the limits.
#' @param data The data the model was fitted to, when they cannot be found.
#' @param marginal Bayesian fits only (\code{brms} with a \code{weibull()}, \code{lognormal()} or
#' \code{exponential()} family): \code{FALSE} gives the curves of a typical cluster (random effects at zero),
#' \code{TRUE} the curves averaged over the random effects of each draw (the survival of the population).
#' A Bayesian fit's curves and medians are posterior medians of each draw's S(t) and median, with equal-tailed
#' pointwise limits. brms \code{cox()}: S(t) = exp(-H0(t) exp(eta)) with H0 the integrated spline baseline hazard of
#' each draw (the curves stop at the spline's upper boundary); medians whose draws partly lie beyond it are given
#' when fewer than half do, with their share in column \code{beyond}. Not available: a shape or sigma modelled by
#' predictors. With random slopes the variance at each pattern row is z' Sigma z. The average over the
#' random effects is the
#' checked quadrature of \code{bias_adjust} (Gauss-Hermite, then the trapezoid rule in z, then adaptive integration,
#' until two rules agree to 1e-8).
#' @return An object of class \code{pm_survmeans}: \code{curves} (the levels, \code{time}, \code{surv},
#' \code{conf.low}, \code{conf.high}), \code{medians} (the levels, \code{median}, \code{conf.low},
#' \code{conf.high}; \code{NA} when the curve does not fall to 0.5) and \code{settings} (the pattern of the other
#' variables, the method). \code{autoplot()} draws the curves.
#' @seealso \code{\link{predictmeans}} for hazard ratios and time ratios between the levels.
#' @examples
#' library(survival)
#' lung2 <- na.omit(lung[, c("time", "status", "ph.ecog", "sex", "age")])
#' lung2$ecog <- factor(lung2$ph.ecog)
#' lung2$sex <- factor(lung2$sex)
#' sm <- survmeans(coxph(Surv(time, status) ~ ecog + sex + age, data = lung2), "ecog",
#' at = list(sex = "2"))
#' sm$medians
#' ggplot2::autoplot(sm)
#' @export
survmeans <- function(model, modelterm, at = NULL, times = NULL, conf_level = 0.95, data = NULL, marginal = FALSE) {
if (inherits(model, pm_bayes_classes)) { # (Bayesian fits: curves for each draw, R/bayes.R)
return(pm_bayes_survmeans(pm_bayes_wrap(model), modelterm, at, times, conf_level, marginal))
}
if (!isFALSE(marginal)) {
stop("'marginal' is for Bayesian fits (survival averaged over the random effects of each draw).", call. = FALSE)
}
pm_need("survival", "survival models")
if (!inherits(model, c("coxph", "survreg")) || inherits(model, "coxme")) {
stop("survmeans() handles coxph and survreg fits (coxme has no survival curves for new data).", call. = FALSE)
}
if (!is.numeric(conf_level) || length(conf_level) != 1 || conf_level <= 0 || conf_level >= 1) {
stop("'conf_level' must be a number between 0 and 1.", call. = FALSE)
}
if (inherits(model, "survreg") && length(model$scale) > 1) {
stop("survmeans() of a survreg model with strata() (a scale per stratum) is not available; fit a model per ",
"stratum.", call. = FALSE)
}
strata_vars <- if (inherits(model, "coxph")) pm_surv_special_vars(model, "strata")
info <- pm_model_info(model, data)
info$extra_vars <- unique(c(info$extra_vars, strata_vars)) # (left out of the fixed terms)
d <- pm_recover_data(info)$data
tt <- stats::delete.response(pm_fixed_terms(model))
used <- unique(c(all.vars(tt), strata_vars))
pt <- pm_surv_pattern(d, modelterm, used, at)
pat <- pt$pat
levs <- pt$levs
nd <- pt$nd
pm_surv_basis_check(model, nd)
z <- stats::qnorm(1 - (1 - conf_level) / 2)
res <- if (inherits(model, "coxph")) pm_surv_cox(model, nd, levs, times, conf_level) else
pm_surv_aft(model, nd, levs, times, z, d)
out <- list(curves = res$curves, medians = res$medians,
settings = list(modelterm = modelterm, at = pat, conf_level = conf_level,
method = res$method, model_class = class(model)[1],
version = as.character(utils::packageVersion("predictmeans"))))
class(out) <- "pm_survmeans"
out
}
## Cox: survfit() at each pattern, one row at a time (in a stratified fit each row has the baseline of its
## stratum, with its own times); beyond the last follow-up time S(t) is not estimated (NA), not carried forward
pm_surv_cox <- function(model, nd, levs, times, conf_level) {
one <- lapply(seq_len(nrow(nd)), function(j) {
sf <- survival::survfit(model, newdata = nd[j, , drop = FALSE], conf.int = conf_level, conf.type = "log")
tmax <- max(sf$time)
tm <- if (is.null(times)) c(0, sf$time) else sort(unique(c(0, times)))
s <- summary(sf, times = pmin(tm, tmax), extend = TRUE)
out <- tm > tmax
q <- suppressWarnings(stats::quantile(sf, probs = 0.5, conf.int = TRUE))
list(curve = data.frame(levs[rep(j, length(tm)), , drop = FALSE], time = tm,
surv = replace(s$surv, out, NA), conf.low = replace(s$lower, out, NA),
conf.high = replace(s$upper, out, NA), row.names = NULL),
median = data.frame(levs[j, , drop = FALSE], median = as.numeric(q$quantile)[1],
conf.low = as.numeric(q$lower)[1], conf.high = as.numeric(q$upper)[1], row.names = NULL))
})
list(curves = do.call(rbind, lapply(one, `[[`, "curve")), medians = do.call(rbind, lapply(one, `[[`, "median")),
method = paste0("survfit() of the Cox model (", model$method, " ties)"))
}
## The covariate pattern must give every coefficient a column (stops for tt(), pspline(), ...: R/adapter-survival.R)
pm_surv_basis_check <- function(model, nd) {
X <- if (inherits(model, "coxph")) pm_surv_basis(model, nd, pm_contrasts(model)) else
pm_basis.survreg(model, nd, pm_contrasts(model))
invisible(X)
}
## AFT: S(t) = 1 - F((log t - eta)/sigma), delta method over (beta, log sigma)
pm_surv_aft <- function(model, nd, levs, times, z, d) {
dist <- survival::survreg.distributions[[model$dist]]
base <- if (is.null(dist$dist)) dist else survival::survreg.distributions[[dist$dist]]
if (is.null(dist$trans) || !isTRUE(all.equal(dist$trans(c(1, 2)), log(c(1, 2))))) {
stop("survmeans() needs a survreg distribution on the log-time scale (weibull, lognormal, loglogistic, ",
"exponential).", call. = FALSE)
}
b <- stats::coef(model)
b <- b[!is.na(b)]
X <- pm_basis.survreg(model, nd, contrasts = pm_contrasts(model))[, names(b), drop = FALSE]
eta <- drop(X %*% b)
V <- as.matrix(stats::vcov(model))
fixed_scale <- !("Log(scale)" %in% rownames(V))
sig <- model$scale
if (is.null(times)) times <- seq(0, max(d[[all.vars(stats::formula(model)[[2]])[1]]], na.rm = TRUE), length.out = 101)
times <- sort(unique(times))
idx <- c(names(b), if (!fixed_scale) "Log(scale)")
Vb <- V[idx, idx, drop = FALSE]
curves <- do.call(rbind, lapply(seq_along(eta), function(j) {
tpos <- pmax(times, .Machine$double.xmin)
w <- (log(tpos) - eta[j]) / sig
den <- base$density(w, model$parms)
S <- ifelse(times <= 0, 1, den[, 2]) # 1 - F(w)
f <- den[, 3]
G <- cbind(outer(f / sig, X[j, ]), # dS/dbeta = f/sigma x
if (!fixed_scale) f * w) # dS/dlog(sigma) = f w
se <- sqrt(rowSums((G %*% Vb) * G))
se_log <- ifelse(S > 0, se / S, NA_real_)
data.frame(levs[rep(j, length(times)), , drop = FALSE], time = times, surv = S,
conf.low = ifelse(times <= 0, 1, S * exp(-z * se_log)),
conf.high = ifelse(times <= 0, 1, pmin(1, S * exp(z * se_log))), row.names = NULL)
}))
q50 <- base$quantile(0.5, model$parms)
med <- exp(eta + sig * q50)
Gm <- cbind(X, if (!fixed_scale) sig * q50) # d log(median) / d(beta, log sigma)
se_lm <- sqrt(rowSums((Gm %*% Vb) * Gm))
medians <- data.frame(levs, median = med, conf.low = med * exp(-z * se_lm), conf.high = med * exp(z * se_lm),
row.names = NULL)
list(curves = curves, medians = medians, method = paste0("survreg (", model$dist, "), delta method"))
}
#' @export
print.pm_survmeans <- function(x, ...) {
s <- x$settings
cat("Survival curves of '", s$modelterm, "' (", s$method, "); ", s$conf_level * 100, "% pointwise limits\n",
sep = "")
if (length(s$at)) cat("At: ", pm_surv_at_text(s$at), "\n", sep = "")
cat("\nMedian survival time:\n")
print(x$medians, row.names = FALSE)
cat("\n(", nrow(x$curves), " rows of S(t) in $curves; autoplot() draws them)\n", sep = "")
pm_print_advice(x)
invisible(x)
}
#' @rdname survmeans
#' @param object A \code{survmeans()} result.
#' @param limits Draw the pointwise limits as bands.
#' @param \dots Not used.
#' @exportS3Method ggplot2::autoplot pm_survmeans
autoplot.pm_survmeans <- function(object, limits = TRUE, ...) {
s <- object$settings
cv <- object$curves
vars <- strsplit(s$modelterm, ":", fixed = TRUE)[[1]]
# one colour per level of the first factor; the other factors of the term as panels
cv$curve <- factor(cv[[vars[1]]])
panel <- vars[-1]
cox <- grepl("^survfit", s$method)
sty <- pm_style_defaults
p <- ggplot2::ggplot(cv, ggplot2::aes(x = .data$time, y = .data$surv, colour = .data$curve))
if (limits) {
p <- p + if (cox) {
list(ggplot2::geom_step(ggplot2::aes(y = .data$conf.low), linetype = 3, na.rm = TRUE),
ggplot2::geom_step(ggplot2::aes(y = .data$conf.high), linetype = 3, na.rm = TRUE))
} else {
ggplot2::geom_ribbon(ggplot2::aes(ymin = .data$conf.low, ymax = .data$conf.high, fill = .data$curve),
colour = NA, alpha = sty$alpha / 2, na.rm = TRUE)
}
}
p <- p + (if (cox) ggplot2::geom_step(linewidth = 0.8) else ggplot2::geom_line(linewidth = 0.8)) +
ggplot2::geom_hline(yintercept = 0.5, linetype = 2, colour = sty$guide) +
ggplot2::scale_y_continuous(limits = c(0, 1)) +
ggplot2::guides(fill = "none") + pm_group_scales(sty, nlevels(cv$curve)) +
(if (length(panel)) ggplot2::facet_wrap(stats::as.formula(paste("~", paste(sprintf("`%s`", panel), collapse = "+"))),
labeller = ggplot2::label_both)) +
ggplot2::labs(x = "time", y = "survival probability", colour = vars[1],
title = pm_wrap_title(paste0("Survival curves of '", s$modelterm, "'",
if (limits) paste0(" with ", s$conf_level * 100, "% pointwise limits")), 14),
caption = pm_wrap_title(paste0(if (length(s$at)) paste0("At ", pm_surv_at_text(s$at), "; "),
"dashed line: median survival"), 11, rel = 1)) +
pm_theme()
p
}
#' @rdname survmeans
#' @param x A \code{survmeans()} result, for \code{plot()}: it draws \code{autoplot()} and returns it invisibly.
#' @exportS3Method plot pm_survmeans
plot.pm_survmeans <- function(x, ...) pm_plot_via_autoplot(x, ...)
## "sex = 2, age = 62.43": the covariate pattern of the curves
pm_surv_at_text <- function(at) {
paste(names(at), vapply(at, function(v) if (is.numeric(v)) format(signif(v, 4)) else as.character(v), ""),
sep = " = ", collapse = ", ")
}
## The covariate pattern of the curves: the levels of 'modelterm', the other variables at 'at', numeric ones at their
## means, factors at their first level (said). Returns list(pat, levs, nd).
pm_surv_pattern <- function(d, modelterm, used, at) {
vars <- strsplit(modelterm, ":", fixed = TRUE)[[1]]
if (!all(vars %in% used)) stop("'", modelterm, "' is not made of variables of the model.", call. = FALSE)
bad <- setdiff(names(at), used)
if (length(bad)) stop("'at' names variables that are not in the model: ", paste(bad, collapse = ", "), ".",
call. = FALSE)
if (!all(vapply(d[vars], function(z) is.factor(z) || is.character(z), logical(1)))) {
stop("'modelterm' must be made of factors; for a covariate give its values in 'at'.", call. = FALSE)
}
# the covariate pattern of the other variables: 'at', numeric means, first levels (said)
other <- setdiff(used, vars)
pat <- list()
first <- character(0)
for (v in other) {
x <- d[[v]]
if (!is.null(at[[v]])) {
if (length(at[[v]]) != 1) stop("'at' gives one value per variable.", call. = FALSE)
pat[[v]] <- if (is.factor(x)) factor(at[[v]], levels = levels(x)) else at[[v]]
if (is.factor(x) && is.na(pat[[v]])) stop("'", at[[v]], "' is not a level of '", v, "'.", call. = FALSE)
} else if (is.factor(x) || is.character(x)) {
x <- factor(x)
pat[[v]] <- factor(levels(x)[1], levels = levels(x))
first <- c(first, paste0(v, " = ", levels(x)[1]))
} else {
pat[[v]] <- mean(x, na.rm = TRUE)
}
}
if (length(first)) message("survmeans(): curves at ", paste(first, collapse = ", "),
" (the first level; give 'at' or include the factor in 'modelterm').")
levs <- expand.grid(lapply(d[vars], function(z) levels(factor(z))), KEEP.OUT.ATTRS = FALSE, stringsAsFactors = TRUE)
nd <- levs
for (v in names(pat)) nd[[v]] <- rep(pat[[v]], nrow(nd))
list(pat = pat, levs = levs, nd = nd)
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.