Skip to contents

Compute martingale and deviance residuals for Cox models without materialising intermediate survival fits in R. The functions rely on dedicated C++ implementations that operate either on in-memory vectors or on bigmemory::big.matrix objects to enable streaming computations on large datasets.

Usage

cox_deviance_residuals(time, status, weights = NULL)

cox_deviance_details(time, status, weights = NULL)

cox_deviance_residuals_big(X, time_col, status_col, weights = NULL)

cox_partial_deviance_big(X, coef, time, status)

benchmark_deviance_residuals(time, status, iterations = 25, methods = list())

Arguments

time

Numeric vector of follow-up times.

status

Numeric or integer vector of the same length as time giving the event indicators (1 for an event, 0 for censoring).

weights

Optional non-negative case weights. When supplied they must have the same length as time.

X

A bigmemory::big.matrix storing the survival information column-wise.

time_col, status_col

Integer indices pointing to the columns of X that contain the follow-up time and event indicator respectively.

coef

Numeric vector of regression coefficients used to evaluate the partial log-likelihood and deviance on a big.matrix design.

iterations

Number of iterations used by bench::mark when benchmarking the residual computations.

methods

Optional named list of alternative residual implementations to compare against in benchmark_deviance_residuals.

Value

  • cox_deviance_residuals() and cox_deviance_residuals_big() return a numeric vector of deviance residuals.

  • cox_deviance_details() returns a list with cumulative hazard, martingale, and deviance residuals.

  • cox_partial_deviance_big() returns a list containing the partial log-likelihood, deviance, and the evaluated linear predictor.

  • benchmark_deviance_residuals() returns a tibble::tibble.

Details

  • cox_deviance_residuals() operates on standard R vectors and matches the output of residuals(coxph(...), type = "deviance") for right-censored data without ties.

  • cox_deviance_residuals_big() keeps the computation in C++ while reading directly from a big.matrix, avoiding extra copies.

  • cox_partial_deviance_big() evaluates the partial log-likelihood and deviance for a given coefficient vector and big design matrix. This is useful when selecting the number of latent components via information criteria.

benchmark_deviance_residuals() compares the dedicated C++ implementation against reference approaches (for example, the survival package) using bench::mark. The function returns a tibble with iteration statistics.

Examples

if (requireNamespace("survival", quietly = TRUE)) {
  set.seed(123)
  time <- rexp(50)
  status <- rbinom(50, 1, 0.6)
  dr_cpp <- cox_deviance_residuals(time, status)
  dr_surv <- residuals(survival::coxph(survival::Surv(time, status) ~ 1),
                       type = "deviance")
  all.equal(unname(dr_cpp), unname(dr_surv), tolerance = 1e-6)
}
#> [1] TRUE