R/gcecox.R

Defines functions .gcecox_fit .gce_default_t .gce_hazard_object gcecox.default gcecox.formula gcecox

Documented in gcecox gcecox.default gcecox.formula

#' Generalized competing event model via cause-specific Cox regression
#'
#' @description
#' Fits a generalized competing event (GCE) model on the cause-specific hazard
#' scale and estimates covariate effects on \eqn{\omega^{+}} (event of interest
#' vs. competing event) using the Lunn-McNeil stacked model (see
#' \code{\link{lunnmcneil}}), with confidence intervals, Wald tests, and an
#' omnibus test. A GCE risk score is formed from the model linear predictor.
#'
#' @details
#' The model is specified with a formula whose response is
#' \code{Surv(time, status)}; see the \emph{Interfaces} section of
#' \code{\link{lunnmcneil}} for the accepted status codings. The fitted object
#' stores the model terms, factor levels, and contrasts, so that
#' \code{\link[=predict.gcemod]{predict}()} can evaluate the risk score and the
#' predicted \eqn{\omega^{+}} for new data.
#'
#' Fitting does not depend on a time point. The argument \code{t} only sets the
#' default readout time for quantities that are functions of time: the
#' predicted absolute \eqn{\omega^{+}(t)} and \eqn{\omega(t)}
#' (\code{predict(type = "ratio")}, \code{type = "share"}), calibration
#' (\code{\link{gce_calibration}}), and the time axis of the displays. It can
#' be overridden in each of those functions.
#'
#' The default method is the matrix interface of earlier versions,
#' \code{gcecox(Time, Ind, Cov, t = )}, retained for backward compatibility.
#'
#' @param formula a formula with a \code{Surv(time, status)} response (formula
#'   method), or the numeric vector of follow-up times (default method, where
#'   it may also be named \code{Time}).
#' @param data a data frame in which the formula is evaluated.
#' @param subset,na.action as in \code{\link[stats]{model.frame}}.
#' @param t default readout time for time-dependent quantities. If \code{NULL}
#'   (default), the largest observed event time is used.
#' @param event,competing code (or factor level) marking the event of interest
#'   and the competing event; see \code{\link{lunnmcneil}}.
#' @param conf.level confidence level (default \code{0.95}).
#' @param cluster.se logical; cluster-robust SEs in the Lunn-McNeil model
#'   (default \code{TRUE}).
#' @param standardize logical; controls only the \emph{reported} omega+ ratio
#'   scale (default \code{FALSE} = per natural covariate unit; \code{TRUE} =
#'   per 1 SD). The risk score is \emph{always} the normalized (mean-centered)
#'   linear predictor regardless of this setting, so cutpoints, plots, and
#'   calibration are unaffected. Covariate means/SDs are returned by
#'   \code{\link{gce_scaling}}.
#' @param contrasts optional contrasts specification passed to
#'   \code{\link[stats]{model.matrix}}.
#' @param model logical; keep the model frame in the fitted object (default
#'   \code{TRUE}).
#' @param Ind (default method) a data frame of event indicators. Column 1 =
#'   event of interest, column 2 = competing event (\code{0}/\code{1}).
#' @param Cov (default method) a data frame of covariates.
#' @param M deprecated and ignored. The number of bins is now an argument of
#'   the displays (\code{plot(fit, which = "riskscore", bins = )},
#'   \code{\link{gce_calibration}}).
#' @param ... passed to \code{\link[survival]{coxph}} for the stacked model.
#'
#' @return An object of class \code{c("gcecox", "gcemod")}. The components most
#'   often needed are available through methods rather than by name; see
#'   \code{\link{gcemod-methods}} (\code{print}, \code{summary}, \code{coef},
#'   \code{vcov}, \code{confint}, \code{logLik}, \code{nobs}, \code{formula},
#'   \code{terms}, \code{model.frame}, \code{model.matrix}, \code{predict},
#'   \code{fitted}, \code{update}, \code{plot}). The list also contains
#'   \code{coef} and \code{var} (log omega+ ratios and their covariance matrix
#'   on the reported scale), \code{riskscore} (mean-centered linear predictor),
#'   \code{omegaplus} and \code{omega} (per-subject predictions at \code{t}),
#'   \code{omnibus}, \code{lunnmcneil} (the stacked-model fit), \code{scaling},
#'   and the model \code{terms}, \code{xlevels}, \code{contrasts}, and
#'   \code{model} frame.
#'
#' @examples
#' data(hn)
#' fit <- gcecox(Surv(time, status) ~ age + smoker + t_cat + n_cat + p16,
#'               data = hn)
#' fit
#' summary(fit)
#' confint(fit)
#'
#' # risk score and predicted omega+ at 5 years for new subjects
#' predict(fit, newdata = hn[1:3, ], type = "lp")
#' predict(fit, newdata = hn[1:3, ], type = "ratio", times = 5)
#'
#' # matrix interface
#' Ind <- data.frame(event = as.integer(hn$status == 1),
#'                   competing = as.integer(hn$status == 2))
#' gcecox(hn$time, Ind, hn[, c("age", "smoker", "p16")], t = 5)
#' @seealso \code{\link{gcefg}}, \code{\link{gcecif}}, \code{\link{lunnmcneil}},
#'   \code{\link{gcemod-methods}}, \code{\link{gce_cutpoints}}
#' @export
gcecox <- function(formula, ...) {
  if (missing(formula)) {
    r <- .gce_legacy_redispatch(sys.call(), parent.frame())
    if (!is.null(r)) return(r$value)
  }
  UseMethod("gcecox")
}

#' @rdname gcecox
#' @export
gcecox.formula <- function(formula, data, subset, na.action, t = NULL,
                           event = NULL, competing = NULL,
                           conf.level = 0.95, cluster.se = TRUE,
                           standardize = FALSE, contrasts = NULL,
                           model = TRUE, ...) {
  cl <- match.call(); cl[[1L]] <- quote(gcecox)
  d <- .gce_design_formula(formula, match.call(expand.dots = FALSE),
                           parent.frame(), event, competing, contrasts)
  .gcecox_fit(d, t = t, conf.level = conf.level, cluster.se = cluster.se,
              standardize = standardize, model = model, call = cl, ...)
}

#' @rdname gcecox
#' @export
gcecox.default <- function(formula, Ind, Cov, M = NULL, t = NULL,
                           conf.level = 0.95, cluster.se = TRUE,
                           standardize = FALSE, ...) {
  cl <- match.call(); cl[[1L]] <- quote(gcecox)
  .gce_M_deprecated(M)
  Time <- formula
  d <- .gce_design_default(Time, .gce_ind_cause(Time, Ind), Cov)
  .gcecox_fit(d, t = t, conf.level = conf.level, cluster.se = cluster.se,
              standardize = standardize, model = TRUE, call = cl, ...)
}

# Components common to the two hazard-scale fits.
.gce_hazard_object <- function(d, lm.fit, t, conf.level, standardize, model,
                               call, method) {
  cn <- lm.fit$covnames
  Xd <- d$X[, cn, drop = FALSE]
  ctr <- lm.fit$center[cn]; sds <- lm.fit$scale[cn]
  coef_raw <- lm.fit$coef_raw[cn]
  coef_std <- coef_raw * sds
  ## Risk score: always the normalized (mean-centered) linear predictor, i.e.
  ## the raw coefficients on mean-centered covariates. Independent of the
  ## reported coefficient scale; the average subject has riskscore = 0.
  riskscore <- as.numeric(sweep(Xd, 2, ctr, "-") %*% coef_raw)
  normCER <- as.numeric(scale(riskscore))

  op <- lm.fit$omegaplus
  result <- cbind(`exp(coef) (omega+ ratio)` = op$omegaplus_ratio,
                  `lower .95` = op$conf.low,
                  `upper .95` = op$conf.high,
                  `P-value`   = op$p.value)
  rownames(result) <- op$term

  scaling <- data.frame(term = cn, mean = as.numeric(ctr), sd = as.numeric(sds),
                        coef_perSD = as.numeric(coef_std),
                        omegaplus_ratio_perSD = exp(as.numeric(coef_std)),
                        row.names = NULL, stringsAsFactors = FALSE)
  list(
    call = call, formula = d$formula, terms = d$terms, xlevels = d$xlevels,
    contrasts = d$contrasts, na.action = d$na.action,
    model = if (isTRUE(model)) d$model else NULL,
    method = method,
    coef = lm.fit$coef, var = lm.fit$var, result = result,
    coef_raw = coef_raw, coef_std = coef_std,
    center = ctr, scale = sds, scaling = scaling,
    omnibus = lm.fit$omnibus, lunnmcneil = lm.fit,
    riskscore = riskscore, normCER = normCER,
    time = d$time, cause = d$cause, design = Xd,
    covnames = cn, covariate.names = d$covariate.names,
    n = d$n, n_event = sum(d$cause == 1L), n_competing = sum(d$cause == 2L),
    t = t, conf.level = conf.level, standardize = isTRUE(standardize)
  )
}

.gce_default_t <- function(d, t) {
  if (is.null(t)) return(max(d$time[d$cause > 0L]))
  .gce_pos(t, "t")
  t
}

.gcecox_fit <- function(d, t, conf.level, cluster.se, standardize, model,
                        call, ...) {
  t <- .gce_default_t(d, t)
  lm.fit <- .lm_engine(d, type = "coxph", cluster.se = cluster.se,
                       conf.level = conf.level, standardize = standardize, ...)
  obj <- .gce_hazard_object(d, lm.fit, t, conf.level, standardize, model,
                            call, method = "Cox (cause-specific)")

  ## Marginal Nelson-Aalen cause-specific cumulative hazards: the baseline of
  ## the predicted absolute omega+(t) = {H1(t) / H2(t)} * exp(riskscore).
  md <- data.frame(Time = d$time, CA = as.integer(d$cause == 1L),
                   CM = as.integer(d$cause == 2L))
  sf.ca <- survfit(Surv(Time, CA) ~ 1, data = md)
  sf.cm <- survfit(Surv(Time, CM) ~ 1, data = md)
  obj$cumhaz <- list(event     = list(time = sf.ca$time, cumhaz = sf.ca$cumhaz),
                     competing = list(time = sf.cm$time, cumhaz = sf.cm$cumhaz))
  obj$w0plus <- .cumhaz_at(obj$cumhaz$event, t) /
                .cumhaz_at(obj$cumhaz$competing, t)
  obj$omegaplus <- obj$w0plus * exp(obj$riskscore)       # per-subject omega+
  obj$omega     <- obj$omegaplus / (1 + obj$omegaplus)   # per-subject omega
  structure(obj, class = c("gcecox", "gcemod"))
}

Try the gcemod package in your browser

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

gcemod documentation built on Dec. 1, 2026, 1:06 a.m.