R/utils.R

Defines functions .fmt_p .aj_cif_at .cumhaz_at .gce_coeftab .gce_legacy_redispatch .gce_M_deprecated .gce_pos .gce_newX .gce_ind_cause .gce_design_default .gce_design_formula .gce_finish_design .gce_cause

# Internal helpers for gcemod. Not exported.

# ---------------------------------------------------------------------------
# Model-frame construction
#
# Every fitter (formula or matrix interface) reduces its input to the same
# internal "design" list:
#   time, cause (0 = censored, 1 = event of interest, 2 = competing event),
#   X (numeric design matrix, no intercept, constant columns removed),
#   terms (response-free terms object), xlevels, contrasts, model (model
#   frame), formula, na.action, covariate.names.
# Storing terms / xlevels / contrasts is what allows predict() to rebuild the
# design matrix for new data.
# ---------------------------------------------------------------------------

#' Map a status variable to the internal 0/1/2 cause coding
#' @keywords internal
#' @noRd
.gce_cause <- function(status, event = NULL, competing = NULL) {
  if (inherits(status, "Surv"))
    stop("The response must be written as Surv(time, status).", call. = FALSE)
  if (is.logical(status))
    stop("'status' must distinguish two event types; a logical status has ",
         "only one. Use a factor or the codes 0 (censored), 1, 2.",
         call. = FALSE)
  if (is.factor(status)) {
    lev <- levels(status)
    if (length(lev) < 3L)
      stop("A factor 'status' needs at least three levels: censored (first ",
           "level), event of interest, and competing event.", call. = FALSE)
    if (is.null(event)) event <- lev[2L]
    if (is.null(competing)) {
      rest <- setdiff(lev[-1L], event)
      if (length(rest) != 1L)
        stop("'status' has more than two event types; name the competing ",
             "event with 'competing' (and combine other causes beforehand).",
             call. = FALSE)
      competing <- rest
    }
    event <- as.character(event); competing <- as.character(competing)
    if (!all(c(event, competing) %in% lev))
      stop("'event' and 'competing' must be levels of the status factor.",
           call. = FALSE)
    censor <- lev[1L]
    status <- as.character(status)
  } else {
    if (!is.numeric(status))
      stop("'status' must be numeric (0 = censored) or a factor.",
           call. = FALSE)
    if (is.null(event)) event <- 1
    if (is.null(competing)) competing <- 2
    censor <- 0
  }
  if (identical(event, competing))
    stop("'event' and 'competing' must differ.", call. = FALSE)
  bad <- !is.na(status) & !(status %in% c(censor, event, competing))
  if (any(bad))
    stop("'cause' contains codes other than 0, 'event', and 'competing'. ",
         "Recode multi-cause data to a single competing category first.",
         call. = FALSE)
  cause <- rep(NA_integer_, length(status))
  cause[status == censor]    <- 0L
  cause[status == event]     <- 1L
  cause[status == competing] <- 2L
  attr(cause, "codes") <- list(event = event, competing = competing)
  cause
}

#' Finish a design list from a response-free model frame
#' @keywords internal
#' @noRd
.gce_finish_design <- function(mf, time, cause, formula, contrasts = NULL,
                               covariate.names = NULL) {
  tt <- attr(mf, "terms")
  if (!is.numeric(time)) stop("'Time' must be numeric.", call. = FALSE)
  if (any(time < 0, na.rm = TRUE))
    stop("'Time' must be non-negative.", call. = FALSE)

  X <- stats::model.matrix(tt, mf, contrasts.arg = contrasts)
  ctr <- attr(X, "contrasts")
  X <- X[, colnames(X) != "(Intercept)", drop = FALSE]
  if (ncol(X) < 1L)
    stop("The model must contain at least one covariate.", call. = FALSE)
  # A constant column is collinear with the baseline and makes the stacked
  # models unidentifiable; drop it with a warning rather than failing.
  const <- apply(X, 2L, function(x) !(stats::sd(x, na.rm = TRUE) > 0))
  if (any(const)) {
    warning(sprintf("Dropping constant covariate(s): %s.",
                    paste(colnames(X)[const], collapse = ", ")), call. = FALSE)
    X <- X[, !const, drop = FALSE]
  }
  if (ncol(X) < 1L)
    stop("No usable (non-constant) covariates remain.", call. = FALSE)
  attr(X, "assign") <- NULL; attr(X, "contrasts") <- NULL

  codes <- attr(cause, "codes"); attr(cause, "codes") <- NULL
  if (is.null(covariate.names)) covariate.names <- all.vars(tt)
  list(time = as.numeric(time), cause = as.integer(cause), X = X,
       terms = tt, xlevels = stats::.getXlevels(tt, mf), contrasts = ctr,
       model = mf, formula = formula, na.action = attr(mf, "na.action"),
       covariate.names = covariate.names, codes = codes, n = nrow(X))
}

#' Design list from a formula with a Surv(time, status) response
#'
#' \code{mcall} is the matched call of the calling method (so that
#' \code{data}, \code{subset} and \code{na.action} are evaluated in the user's
#' frame, as in \code{lm()} or \code{coxph()}). The two components of the
#' response are carried through \code{model.frame()} as extra variables so that
#' \code{subset} and \code{na.action} apply to them, and so that a numeric
#' 0/1/2 status is accepted directly (\code{survival::Surv()} itself would
#' reject it).
#' @keywords internal
#' @noRd
.gce_design_formula <- function(formula, mcall, env, event = NULL,
                                competing = NULL, contrasts = NULL) {
  if (!inherits(formula, "formula") || length(formula) != 3L)
    stop("'formula' must be a two-sided formula with a Surv(time, status) ",
         "response.", call. = FALSE)
  lhs <- formula[[2L]]
  fn <- if (is.call(lhs)) paste(deparse(lhs[[1L]]), collapse = "") else ""
  if (!fn %in% c("Surv", "survival::Surv") || length(lhs) != 3L)
    stop("The response must be of the form Surv(time, status), with 'status' ",
         "coded 0 = censored, 1 = event of interest, 2 = competing event ",
         "(or a factor whose first level is censoring).", call. = FALSE)
  args <- as.list(lhs)[-1L]
  nm <- names(args); if (is.null(nm)) nm <- c("", "")
  ti <- if ("time" %in% nm) which(nm == "time") else which(nm == "")[1L]
  time_expr   <- args[[ti]]
  status_expr <- args[[setdiff(1:2, ti)]]

  has_data <- "data" %in% names(mcall)
  tt <- if (has_data) stats::terms(formula, data = eval(mcall$data, env))
        else stats::terms(formula)
  attr(tt, "intercept") <- 1L
  rhs <- stats::formula(stats::delete.response(tt))
  environment(rhs) <- environment(formula)

  m <- match(c("data", "subset", "na.action"), names(mcall), 0L)
  mf <- mcall[c(1L, m)]
  mf$formula <- rhs
  mf[["gce.time"]]   <- time_expr
  mf[["gce.status"]] <- status_expr
  mf$drop.unused.levels <- TRUE
  mf[[1L]] <- quote(stats::model.frame)
  mf <- eval(mf, env)

  time  <- mf[["(gce.time)"]]
  cause <- .gce_cause(mf[["(gce.status)"]], event, competing)
  .gce_finish_design(mf, time, cause, formula, contrasts)
}

#' Design list from the matrix interface (Time, cause, Cov)
#' @keywords internal
#' @noRd
.gce_design_default <- function(Time, cause, Cov) {
  Cov <- as.data.frame(Cov)
  if (!is.numeric(Time)) stop("'Time' must be numeric.", call. = FALSE)
  if (length(Time) != nrow(Cov) || length(cause) != nrow(Cov))
    stop("'Time', 'cause', and 'Cov' must have the same number of observations.",
         call. = FALSE)
  if (ncol(Cov) < 1L) stop("'Cov' must contain at least one covariate.", call. = FALSE)
  if (is.null(names(Cov)) || any(names(Cov) == "") || anyDuplicated(names(Cov)))
    stop("'Cov' must have unique, non-empty column names.", call. = FALSE)

  keep <- stats::complete.cases(Time, cause, Cov)
  if (!all(keep)) {
    warning(sprintf("Dropping %d row(s) with missing values (complete-case analysis).",
                    sum(!keep)), call. = FALSE)
    Time <- Time[keep]; cause <- cause[keep]; Cov <- Cov[keep, , drop = FALSE]
  }
  # '~ .' (expanded against Cov) tolerates non-syntactic column names.
  tt <- stats::terms(~ ., data = Cov)
  f  <- stats::formula(tt); environment(f) <- globalenv()
  mf <- stats::model.frame(f, data = Cov, na.action = stats::na.pass,
                           drop.unused.levels = TRUE)
  d <- .gce_finish_design(mf, Time, cause, formula = f,
                          covariate.names = names(Cov))
  d$keep <- keep
  d
}

#' Cause coding from the two-column indicator data frame of the matrix interface
#' @keywords internal
#' @noRd
.gce_ind_cause <- function(Time, Ind) {
  Ind <- as.data.frame(Ind)
  if (nrow(Ind) != length(Time))
    stop("'Ind' and 'Time' imply different sample sizes.", call. = FALSE)
  if (ncol(Ind) < 2L)
    stop("'Ind' must have two columns: event of interest, competing event.",
         call. = FALSE)
  CA <- as.integer(Ind[[1L]]); CM <- as.integer(Ind[[2L]])
  cause <- ifelse(is.na(CA) | is.na(CM), NA_integer_, 0L)
  cause[which(CM == 1L)] <- 2L
  cause[which(CA == 1L)] <- 1L          # event of interest wins ties
  cause
}

#' Rebuild the design matrix of a fitted model for new data
#' @keywords internal
#' @noRd
.gce_newX <- function(object, newdata) {
  if (is.null(object$terms))
    stop("This object does not store its model terms; refit with gcemod >= 0.4.0.",
         call. = FALSE)
  newdata <- as.data.frame(newdata)
  miss <- setdiff(all.vars(object$terms), names(newdata))
  if (length(miss))
    stop(sprintf("'newdata' is missing covariate(s): %s.",
                 paste(miss, collapse = ", ")), call. = FALSE)
  mf <- stats::model.frame(object$terms, newdata, na.action = stats::na.pass,
                           xlev = object$xlevels)
  X <- stats::model.matrix(object$terms, mf, contrasts.arg = object$contrasts)
  X[, object$covnames, drop = FALSE]
}

#' Validate a single positive number
#' @keywords internal
#' @noRd
.gce_pos <- function(v, nm) {
  if (!is.numeric(v) || length(v) != 1L || is.na(v) || v <= 0)
    stop(sprintf("'%s' must be a single positive number.", nm), call. = FALSE)
  invisible(v)
}

#' Warn once that the 'M' argument of the fitters is defunct
#' @keywords internal
#' @noRd
.gce_M_deprecated <- function(M) {
  if (!is.null(M))
    warning("Argument 'M' is deprecated and ignored: the number of bins is ",
            "now an argument of the display, e.g. ",
            "plot(fit, which = \"riskscore\", bins = 5).", call. = FALSE)
  invisible(NULL)
}

#' Re-dispatch a matrix-interface call that names its first argument 'Time'
#' @keywords internal
#' @noRd
.gce_legacy_redispatch <- function(mc, env) {
  nm <- names(mc)
  if (is.null(nm) || !"Time" %in% nm) return(NULL)
  nm[nm == "Time"] <- "formula"
  names(mc) <- nm
  list(value = eval(mc, env))
}

#' Wald coefficient table shared by the summary methods
#' @keywords internal
#' @noRd
.gce_coeftab <- function(est, se, z, p, level) {
  zc <- stats::qnorm(1 - (1 - level) / 2)
  coefs <- cbind(coef = est, `exp(coef)` = exp(est), `se(coef)` = se,
                 z = z, `Pr(>|z|)` = p)
  lab <- format(100 * level, trim = TRUE)
  ci <- cbind(exp(est), exp(est - zc * se), exp(est + zc * se))
  colnames(ci) <- c("exp(coef)", paste0("lower .", sub("^0\\.", "", format(level))),
                    paste0("upper .", sub("^0\\.", "", format(level))))
  rownames(coefs) <- rownames(ci) <- names(est)
  list(coefficients = coefs, conf.int = ci)
}

#' Step-function value of a cumulative hazard at requested times
#'
#' Reads the Nelson-Aalen cumulative hazard carried by a \code{survfit} object
#' and evaluates it at \code{times} using a right-continuous step function. This
#' replaces the \code{lm(-log(S) ~ time)} extrapolation used by \pkg{gcerisk}.
#'
#' @param sf a \code{survfit} object (single curve), or a list with elements
#'   \code{time} and \code{cumhaz}.
#' @param times numeric vector of evaluation times.
#' @return numeric vector of cumulative hazards, one per element of \code{times}.
#' @keywords internal
#' @noRd
.cumhaz_at <- function(sf, times) {
  ch <- sf$cumhaz
  tt <- sf$time
  if (is.null(ch)) {
    # Fall back to -log(S) if cumhaz is unavailable.
    ch <- -log(sf$surv)
  }
  ok <- is.finite(ch)
  tt <- tt[ok]; ch <- ch[ok]
  if (length(tt) == 0L) return(rep(NA_real_, length(times)))
  f <- stats::stepfun(tt, c(0, ch))
  f(times)
}

#' Aalen-Johansen cumulative incidence of both causes at a landmark time
#'
#' Returns \code{c(F1, F2)}, the cumulative incidence of the event of interest
#' (cause 1) and the competing event (cause 2) at time \code{t}, from the
#' Aalen-Johansen estimator (product-limit all-cause survivor times the
#' cause-specific increments). Used for the observed cumulative-incidence ratio
#' in \code{\link{gce_calibration}} of a \code{\link{gcecif}} fit.
#'
#' @param time numeric follow-up times.
#' @param cause integer cause coding (0 censored, 1 event of interest, 2 competing).
#' @param t landmark time.
#' @return numeric length-2 vector \code{c(F1, F2)}.
#' @keywords internal
#' @noRd
.aj_cif_at <- function(time, cause, t) {
  ut <- sort(unique(time[cause > 0 & time <= t]))
  if (length(ut) < 1L) return(c(NA_real_, NA_real_))
  Y  <- vapply(ut, function(u) sum(time >= u), numeric(1))
  d1 <- vapply(ut, function(u) sum(time == u & cause == 1L), numeric(1))
  d2 <- vapply(ut, function(u) sum(time == u & cause == 2L), numeric(1))
  haz   <- ifelse(Y > 0, (d1 + d2) / Y, 0)
  Sprev <- c(1, cumprod(1 - haz)[-length(haz)])
  c(sum(Sprev * ifelse(Y > 0, d1 / Y, 0)),
    sum(Sprev * ifelse(Y > 0, d2 / Y, 0)))
}

#' Format a numeric p-value for printing
#' @keywords internal
#' @noRd
.fmt_p <- function(p, eps = 1e-4) {
  ifelse(is.na(p), "NA", format.pval(p, digits = 3, eps = eps))
}

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.