R/lunnmcneil.R

Defines functions .lm_finegray .lm_coxph .lm_engine lunnmcneil.default lunnmcneil.formula lunnmcneil

Documented in lunnmcneil lunnmcneil.default lunnmcneil.formula

#' Lunn-McNeil stacked-model estimation of omega+ ratios
#'
#' @description
#' Estimates covariate effects on \eqn{\omega^{+}} (the ratio of the hazard for
#' the event of interest to the hazard for the competing event) from a single
#' stacked ("augmented") model, following Lunn and McNeil (1995). Each subject
#' contributes one record per event type; the model is stratified by event type
#' and the covariate-by-event-type interaction estimates
#' \eqn{\log(\omega^{+}\text{ ratio})} with model-based standard errors,
#' per-covariate Wald tests, and an omnibus multivariate Wald test.
#'
#' \code{lunnmcneil()} is the estimation engine behind \code{\link{gcecox}} and
#' \code{\link{gcefg}}; use it directly when only the coefficient table and
#' tests are needed, and the GCE fitters when the risk score, predictions, and
#' displays are wanted as well.
#'
#' @details
#' Two hazard scales are supported:
#' \describe{
#'   \item{\code{type = "coxph"}}{Cause-specific hazards. The augmented data set
#'     duplicates each subject into an "event" stratum and a "competing" stratum;
#'     the interaction coefficient is exactly the difference in cause-specific
#'     log-hazards, i.e. \eqn{\log(\omega^{+})}. This is the original Lunn-McNeil
#'     construction and the interaction MLE equals the difference of two separate
#'     cause-specific Cox fits.}
#'   \item{\code{type = "finegray"}}{Subdistribution hazards. Risk-set-weighted
#'     data are generated for each event type with
#'     \code{\link[survival]{finegray}}, stacked, and fit with a single weighted,
#'     event-type-stratified \code{\link[survival]{coxph}}. The interaction
#'     estimates the difference in subdistribution log-hazards. Because subjects
#'     recur across the weighted risk sets, cluster-robust (subject) standard
#'     errors are used. This is an extension of Lunn-McNeil to the
#'     subdistribution scale.}
#' }
#' Subject records are duplicated in both cases, so cluster-robust standard
#' errors (clustered on subject) are the default.
#'
#' @section Interfaces:
#' The formula method is the recommended interface. The response is written
#' \code{Surv(time, status)}, where \code{status} is either numeric with
#' \code{0} = censored and the codes given by \code{event} and \code{competing}
#' (defaults \code{1} and \code{2}), or a factor whose first level denotes
#' censoring (the convention of \code{\link[survival]{Surv}} for multi-state
#' data), in which case \code{event} and \code{competing} default to the second
#' and third levels. The right-hand side accepts the usual model-formula
#' syntax (factors, interactions, transformations, splines). The model terms,
#' factor levels, and contrasts are stored in the fitted object.
#'
#' The default method is the matrix interface of earlier versions
#' (\code{lunnmcneil(Time, cause, Cov)}); it is retained for backward
#' compatibility and returns the same object.
#'
#' @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 cause (default method) event indicator per subject: \code{0} =
#'   censored, and the codes in \code{event} and \code{competing} for the two
#'   event types.
#' @param Cov (default method) a data frame of covariates (factors are expanded
#'   to indicators).
#' @param event code (or factor level) marking the event of interest.
#' @param competing code (or factor level) marking the competing event.
#' @param type \code{"coxph"} (cause-specific, default) or \code{"finegray"}
#'   (subdistribution).
#' @param cluster.se logical; cluster-robust (subject) SEs (default \code{TRUE}).
#' @param conf.level confidence level (default \code{0.95}).
#' @param se standard-error method: \code{"robust"} (default; model-based,
#'   cluster-robust on subject, with the censoring weights treated as fixed) or
#'   \code{"boot"} (subject bootstrap: the stacked model is refit on \code{B}
#'   resamples of subjects, re-estimating the censoring weights within each
#'   resample, so the variance additionally accounts for their estimation).
#'   Mainly relevant for \code{type = "finegray"}; because estimating the
#'   weights reduces the asymptotic variance, the fixed-weights default errs,
#'   if at all, on the conservative side.
#' @param B number of bootstrap resamples when \code{se = "boot"} (default
#'   \code{200}).
#' @param standardize logical; controls only the \emph{reported} coefficient
#'   scale (default \code{FALSE}). \code{FALSE} reports omega+ ratios per natural
#'   covariate unit; \code{TRUE} reports them per 1 SD. This is a
#'   reparameterization, so Wald tests, p-values, and the omnibus test are
#'   identical either way. The covariate means/SDs (\code{$center}, \code{$scale})
#'   are always returned.
#' @param contrasts optional contrasts specification passed to
#'   \code{\link[stats]{model.matrix}}.
#' @param ... passed to \code{\link[survival]{coxph}}.
#'
#' @return An object of class \code{"gce_lunnmcneil"}: a list with the fitted
#'   stacked model (\code{$fit}), the omega+ coefficient table
#'   (\code{$omegaplus}), the coefficient vector and its covariance matrix on
#'   the reported scale (\code{$coef}, \code{$var}), the reference
#'   (competing-event) coefficients (\code{$beta_competing}), the omnibus test
#'   (\code{$omnibus}), the model \code{terms}, \code{xlevels},
#'   \code{contrasts} and \code{formula}, and the hazard scale (\code{$type}).
#'   Methods are available for \code{print}, \code{summary}, \code{coef},
#'   \code{vcov}, \code{confint}, \code{nobs}, \code{logLik}, \code{formula},
#'   and \code{terms}.
#'
#' @references Lunn M, McNeil D (1995) Applying Cox regression to competing
#'   risks. \emph{Biometrics} 51:524-32.
#'
#' @examples
#' data(hn)
#' fit <- lunnmcneil(Surv(time, status) ~ age + smoker + t_cat + n_cat + p16,
#'                   data = hn)
#' fit
#' summary(fit)
#' confint(fit)
#'
#' # subdistribution scale
#' lunnmcneil(Surv(time, status) ~ age + smoker + p16, data = hn,
#'            type = "finegray")
#'
#' # matrix interface
#' lunnmcneil(hn$time, hn$status, hn[, c("age", "smoker", "p16")])
#' @seealso \code{\link{gcecox}}, \code{\link{gcefg}},
#'   \code{\link{gcemod-methods}}
#' @export
lunnmcneil <- function(formula, ...) {
  if (missing(formula)) {
    r <- .gce_legacy_redispatch(sys.call(), parent.frame())
    if (!is.null(r)) return(r$value)
  }
  UseMethod("lunnmcneil")
}

#' @rdname lunnmcneil
#' @export
lunnmcneil.formula <- function(formula, data, subset, na.action,
                               event = NULL, competing = NULL,
                               type = c("coxph", "finegray"),
                               cluster.se = TRUE, conf.level = 0.95,
                               standardize = FALSE, se = c("robust", "boot"),
                               B = 200, contrasts = NULL, ...) {
  type <- match.arg(type); se <- match.arg(se)
  cl <- match.call(); cl[[1L]] <- quote(lunnmcneil)
  d <- .gce_design_formula(formula, match.call(expand.dots = FALSE),
                           parent.frame(), event, competing, contrasts)
  out <- .lm_engine(d, type = type, cluster.se = cluster.se,
                    conf.level = conf.level, standardize = standardize,
                    se_method = se, B = B, ...)
  out$call <- cl
  out
}

#' @rdname lunnmcneil
#' @export
lunnmcneil.default <- function(formula, cause, Cov, event = 1, competing = 2,
                               type = c("coxph", "finegray"),
                               cluster.se = TRUE, conf.level = 0.95,
                               standardize = FALSE, se = c("robust", "boot"),
                               B = 200, ...) {
  type <- match.arg(type); se <- match.arg(se)
  cl <- match.call(); cl[[1L]] <- quote(lunnmcneil)
  Time <- formula
  if (length(cause) != length(Time))
    stop("'Time', 'cause', and 'Cov' must have the same number of observations.",
         call. = FALSE)
  d <- .gce_design_default(Time, .gce_cause(cause, event, competing), Cov)
  out <- .lm_engine(d, type = type, cluster.se = cluster.se,
                    conf.level = conf.level, standardize = standardize,
                    se_method = se, B = B, ...)
  out$call <- cl
  out
}

# ---- estimation engine shared by both interfaces and by gcecox()/gcefg() ----
.lm_engine <- function(d, type = "coxph", cluster.se = TRUE, conf.level = 0.95,
                       standardize = FALSE, se_method = "robust", B = 200,
                       ...) {
  Time <- d$time; cause <- d$cause; X <- d$X
  event <- 1L; competing <- 2L
  cn <- colnames(X)
  p <- ncol(X)
  n <- nrow(X)

  # Covariate means/SDs. Always computed and returned: they define the
  # normalized risk score (centered at the mean covariate profile) and let new
  # subjects be scored. The model is fit on the RAW covariate scale; the per-SD
  # report is obtained by a reparameterization (theta_sd = theta_raw * SD),
  # which leaves the Wald tests, p-values, and omnibus test unchanged.
  center <- colMeans(X)
  scale  <- apply(X, 2, stats::sd)
  names(center) <- names(scale) <- cn

  if (type == "coxph") {
    fit_info <- .lm_coxph(Time, cause, X, cn, event, competing, cluster.se, ...)
  } else {
    fit_info <- .lm_finegray(Time, cause, X, cn, event, competing, ...)
  }
  fit <- fit_info$fit
  idx <- fit_info$idx        # positions of the interaction (omega+) coefficients

  cf <- coef(fit)
  V  <- stats::vcov(fit)
  theta_raw <- cf[idx]
  se_raw    <- sqrt(diag(V)[idx])
  names(theta_raw) <- names(se_raw) <- cn
  Vsub <- V[idx, idx, drop = FALSE]
  dimnames(Vsub) <- list(cn, cn)

  ## Optional subject bootstrap: refit on resampled subjects, re-estimating the
  ## censoring weights within each resample, so the variance accounts for both
  ## the subject reuse across strata and the estimation of the weights.
  if (se_method == "boot") {
    TH <- matrix(NA_real_, B, p)
    for (b in seq_len(B)) {
      ix <- sample.int(n, n, replace = TRUE)
      TH[b, ] <- tryCatch({
        fb <- if (type == "coxph") {
          .lm_coxph(Time[ix], cause[ix], X[ix, , drop = FALSE], cn,
                    event, competing, cluster.se, ...)
        } else {
          .lm_finegray(Time[ix], cause[ix], X[ix, , drop = FALSE], cn,
                       event, competing, ...)
        }
        unname(coef(fb$fit)[fb$idx])
      }, error = function(e) rep(NA_real_, p))
    }
    okb <- stats::complete.cases(TH)
    if (sum(okb) < max(20L, B %/% 2L)) {
      warning("Bootstrap variance unreliable: only ", sum(okb), " of ", B,
              " resamples produced a fit; reporting the robust variance ",
              "instead.", call. = FALSE)
    } else {
      Vsub <- stats::cov(TH[okb, , drop = FALSE])
      dimnames(Vsub) <- list(cn, cn)
      se_raw <- sqrt(diag(Vsub))
      names(se_raw) <- cn
    }
  }

  # Reported scale: raw per-unit (default) or per-SD (standardize = TRUE).
  if (isTRUE(standardize)) {
    theta <- theta_raw * scale
    se    <- se_raw * scale
    Vrep  <- Vsub * tcrossprod(scale)
  } else {
    theta <- theta_raw
    se    <- se_raw
    Vrep  <- Vsub
  }

  zcrit <- stats::qnorm(1 - (1 - conf.level) / 2)
  z <- theta_raw / se_raw                 # invariant to the reporting scale
  pval <- 2 * stats::pnorm(-abs(z))

  omegaplus <- data.frame(
    term            = cn,
    log_ratio       = as.numeric(theta),
    se              = as.numeric(se),
    omegaplus_ratio = exp(as.numeric(theta)),
    conf.low        = exp(theta - zcrit * se),
    conf.high       = exp(theta + zcrit * se),
    z               = as.numeric(z),
    p.value         = as.numeric(pval),
    row.names = NULL, stringsAsFactors = FALSE
  )

  omni <- tryCatch({
    stat <- as.numeric(t(theta_raw) %*% solve(Vsub, theta_raw))
    c(statistic = stat, df = p,
      p.value = stats::pchisq(stat, df = p, lower.tail = FALSE))
  }, error = function(e) {
    warning("Omnibus test could not be computed (singular covariance).",
            call. = FALSE)
    c(statistic = NA_real_, df = p, p.value = NA_real_)
  })

  beta_competing <- cf[fit_info$main_idx]
  names(beta_competing) <- cn

  structure(list(
    call = NULL, formula = d$formula, terms = d$terms, xlevels = d$xlevels,
    contrasts = d$contrasts, na.action = d$na.action,
    type = type, fit = fit,
    coef = stats::setNames(as.numeric(theta), cn), var = Vrep,
    omegaplus = omegaplus, coef_raw = theta_raw, vcov_raw = Vsub,
    beta_competing = beta_competing,
    omnibus = omni, covnames = cn, conf.level = conf.level,
    standardize = isTRUE(standardize), center = center, scale = scale,
    se_method = se_method,
    B = if (se_method == "boot") as.integer(B) else NA_integer_,
    n = n, n_event = sum(cause == event), n_competing = sum(cause == competing)
  ), class = "gce_lunnmcneil")
}

# ---- cause-specific (Cox) Lunn-McNeil augmentation ----
# The model is fit on synthetic, syntactic column names (x1, x2, ...) so the
# formula is robust to arbitrary user covariate names (spaces, punctuation,
# etc.). Coefficients are extracted by position in lunnmcneil() and relabelled
# with the original names, so the synthetic names never surface to the user.
.lm_coxph <- function(Time, cause, X, cn, event, competing, cluster.se, ...) {
  p <- ncol(X); n <- nrow(X)
  vn  <- paste0("x", seq_len(p))            # main-effect names
  vni <- paste0("x", seq_len(p), "_ev")     # interaction names
  Xstack <- rbind(X, X); colnames(Xstack) <- vn
  d1     <- rep(c(1, 0), each = n)          # event-stratum indicator
  Xint   <- Xstack * d1; colnames(Xint) <- vni

  base_df <- data.frame(
    .time   = rep(Time, 2),
    .status = c(as.integer(cause == event), as.integer(cause == competing)),
    .etype  = factor(rep(c("event", "competing"), each = n),
                     levels = c("competing", "event")),
    .id     = rep(seq_len(n), 2),
    check.names = FALSE
  )
  aug <- cbind(base_df, Xstack, Xint)

  termlabels <- c(vn, vni, "strata(.etype)")
  f <- stats::reformulate(termlabels, response = "Surv(.time, .status)")
  fit <- if (isTRUE(cluster.se)) {
    coxph(f, data = aug, cluster = aug$.id, robust = TRUE, ...)
  } else {
    coxph(f, data = aug, ...)
  }
  list(fit = fit, main_idx = seq_len(p), idx = (p + 1L):(2L * p))
}

# ---- subdistribution (Fine-Gray) Lunn-McNeil-style augmentation ----
.lm_finegray <- function(Time, cause, X, cn, event, competing, ...) {
  p <- ncol(X); n <- nrow(X)
  vn  <- paste0("x", seq_len(p))            # synthetic, syntactic names
  vni <- paste0("x", seq_len(p), "_ev")
  colnames(X) <- vn
  fstat <- factor(cause, levels = c(0, event, competing),
                  labels = c("censor", "event", "competing"))
  df <- data.frame(.time = Time, .fstat = fstat, .id = seq_len(n),
                   X, check.names = FALSE)
  # Carry .id through the RHS so finegray() retains it for clustering (it keeps
  # only variables named in the formula).
  covform <- stats::reformulate(c(vn, ".id"),
                                response = "Surv(.time, .fstat)")

  fg_e <- survival::finegray(covform, data = df, etype = "event")
  fg_c <- survival::finegray(covform, data = df, etype = "competing")

  Xe <- as.matrix(fg_e[, vn, drop = FALSE])
  Xc <- as.matrix(fg_c[, vn, drop = FALSE])
  Xstack <- rbind(Xe, Xc); colnames(Xstack) <- vn
  d1     <- c(rep(1, nrow(fg_e)), rep(0, nrow(fg_c)))
  Xint   <- Xstack * d1; colnames(Xint) <- vni

  base_df <- data.frame(
    .start  = c(fg_e$fgstart, fg_c$fgstart),
    .stop   = c(fg_e$fgstop,  fg_c$fgstop),
    .status = c(fg_e$fgstatus, fg_c$fgstatus),
    .wt     = c(fg_e$fgwt,    fg_c$fgwt),
    .etype  = factor(c(rep("event", nrow(fg_e)), rep("competing", nrow(fg_c))),
                     levels = c("competing", "event")),
    .id     = c(fg_e$.id, fg_c$.id),
    check.names = FALSE
  )
  aug <- cbind(base_df, Xstack, Xint)

  termlabels <- c(vn, vni, "strata(.etype)")
  f <- stats::reformulate(termlabels, response = "Surv(.start, .stop, .status)")
  fit <- coxph(f, data = aug, weights = aug$.wt, cluster = aug$.id,
               robust = TRUE, ...)
  list(fit = fit, main_idx = seq_len(p), idx = (p + 1L):(2L * p))
}

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.