Competing risks, cumulative incidence and Gray's test
When death prevents the event you study, 1 − Kaplan–Meier overstates risk. Use cumulative incidence, Gray's test and the right kind of hazard for your question.
What runs in CodeSplash
- STAT246Gray competing risks test Runs in CodeSplash
- Cumulative incidence with competing risks Verified in Python and R
- Fine–Gray competing-risks regression Verified in Python and R
You will be able to
- Explain why 1 − Kaplan–Meier overstates risk when events compete
- Compare cumulative incidence between groups with Gray's test
- Choose between cause-specific hazards and the Fine–Gray model
When another event gets there first
ReadThe mgus2 data follow 1,384 people with a benign blood condition that can progress to a plasma cell malignancy (PCM). Most are elderly.
115 progressed to PCM. 860 died first.
Someone who has died can never progress. That is a competing riskCompeting risksOther events that prevent the one you study, such as death before disease progression., and it isn't the same as censoring: a censored person may still have the event later; a person who died cannot.
Predict the error
PredictPredict first
You treat deaths as censoring, fit Kaplan–Meier for PCM and report 1 − survival as "the risk of PCM by 20 years". How does that compare with the real share who develop PCM?
Reveal
It overstates it, by about twofold here (run the code below). Treating death as censoring pretends those people could still progress at the same rate. In these data, that imaginary world has far more PCM than the real one.
Cumulative incidence
In the appThe cumulative incidence functionCumulative incidenceThe probability of having a given kind of event by time t, when other kinds of event can happen first. estimates the real probability of having each kind of event by time . Aalen–Johansen accumulates hazards among those who have had no event of any kind:
The incidences of all causes and the share still event-free add to one at every time.
View data
| months | cumulative incidence | cause |
|---|---|---|
| 0 | 0 | relapse |
| 0.1000 | 0.0067 | relapse |
| 0.2000 | 0.0200 | relapse |
| 0.4000 | 0.0267 | relapse |
| 0.5000 | 0.0267 | relapse |
| 0.8000 | 0.0333 | relapse |
| 0.9000 | 0.0400 | relapse |
| 1.100 | 0.0467 | relapse |
| 1.200 | 0.0533 | relapse |
| 1.300 | 0.0667 | relapse |
| 1.400 | 0.0733 | relapse |
| 1.500 | 0.0800 | relapse |
| 1.800 | 0.0867 | relapse |
| 2.200 | 0.0867 | relapse |
| 2.300 | 0.0867 | relapse |
| 2.400 | 0.0867 | relapse |
| 2.500 | 0.0867 | relapse |
| 2.800 | 0.0933 | relapse |
| 2.900 | 0.1000 | relapse |
| 3.100 | 0.1000 | relapse |
| 3.400 | 0.1000 | relapse |
| 3.600 | 0.1133 | relapse |
| 3.900 | 0.1267 | relapse |
| 4 | 0.1333 | relapse |
| 4.100 | 0.1467 | relapse |
| 4.200 | 0.1533 | relapse |
| 4.400 | 0.1533 | relapse |
| 4.500 | 0.1600 | relapse |
| 4.600 | 0.1667 | relapse |
| 4.700 | 0.1733 | relapse |
| 4.900 | 0.1800 | relapse |
| 5.200 | 0.1800 | relapse |
| 5.400 | 0.1867 | relapse |
| 5.800 | 0.1933 | relapse |
| 6 | 0.2000 | relapse |
| 6.200 | 0.2000 | relapse |
| 6.300 | 0.2067 | relapse |
| 6.400 | 0.2067 | relapse |
| 6.500 | 0.2067 | relapse |
| 6.800 | 0.2067 | relapse |
| 7.300 | 0.2067 | relapse |
| 7.400 | 0.2133 | relapse |
| 7.500 | 0.2267 | relapse |
| 8 | 0.2333 | relapse |
| 8.400 | 0.2400 | relapse |
| 8.500 | 0.2400 | relapse |
| 9.400 | 0.2400 | relapse |
| 9.700 | 0.2400 | relapse |
| 9.800 | 0.2467 | relapse |
| 10.200 | 0.2533 | relapse |
| 10.500 | 0.2601 | relapse |
| 10.600 | 0.2668 | relapse |
| 10.700 | 0.2736 | relapse |
| 11.100 | 0.2804 | relapse |
| 11.500 | 0.2941 | relapse |
| 12.100 | 0.3010 | relapse |
| 12.600 | 0.3079 | relapse |
| 13 | 0.3149 | relapse |
| 13.300 | 0.3219 | relapse |
| 13.400 | 0.3289 | relapse |
First 60 of 172 rows.
115 events of interest, N = 1384
- pcm events
- 115
- Competing events
- 860
Plots
View data
| Cumulative incidence | upper | lower | Curve | etime |
|---|---|---|---|---|
| 0 | — | — | pcm | 0 |
| 0 | — | — | pcm | 1 |
| 0.0014 | 0.0050 | 0.0003 | pcm | 2 |
| 0.0014 | 0.0050 | 0.0003 | pcm | 3 |
| 0.0022 | 0.0061 | 0.0006 | pcm | 4 |
| 0.0029 | 0.0071 | 0.0010 | pcm | 5 |
| 0.0036 | 0.0081 | 0.0014 | pcm | 6 |
| 0.0036 | 0.0081 | 0.0014 | pcm | 7 |
| 0.0051 | 0.0101 | 0.0023 | pcm | 8 |
| 0.0065 | 0.0120 | 0.0032 | pcm | 9 |
| 0.0080 | 0.0138 | 0.0043 | pcm | 10 |
| 0.0087 | 0.0148 | 0.0048 | pcm | 11 |
| 0.0094 | 0.0157 | 0.0053 | pcm | 12 |
| 0.0101 | 0.0166 | 0.0058 | pcm | 13 |
| 0.0116 | 0.0184 | 0.0069 | pcm | 14 |
| 0.0116 | 0.0184 | 0.0069 | pcm | 15 |
| 0.0123 | 0.0192 | 0.0075 | pcm | 16 |
| 0.0137 | 0.0210 | 0.0086 | pcm | 17 |
| 0.0137 | 0.0210 | 0.0086 | pcm | 18 |
| 0.0137 | 0.0210 | 0.0086 | pcm | 19 |
| 0.0137 | 0.0210 | 0.0086 | pcm | 20 |
| 0.0152 | 0.0227 | 0.0097 | pcm | 21 |
| 0.0159 | 0.0236 | 0.0103 | pcm | 22 |
| 0.0174 | 0.0253 | 0.0114 | pcm | 23 |
| 0.0174 | 0.0253 | 0.0114 | pcm | 24 |
| 0.0174 | 0.0253 | 0.0114 | pcm | 25 |
| 0.0174 | 0.0253 | 0.0114 | pcm | 26 |
| 0.0174 | 0.0253 | 0.0114 | pcm | 27 |
| 0.0174 | 0.0253 | 0.0114 | pcm | 28 |
| 0.0188 | 0.0270 | 0.0126 | pcm | 29 |
| 0.0195 | 0.0279 | 0.0132 | pcm | 30 |
| 0.0195 | 0.0279 | 0.0132 | pcm | 31 |
| 0.0195 | 0.0279 | 0.0132 | pcm | 32 |
| 0.0203 | 0.0287 | 0.0138 | pcm | 33 |
| 0.0210 | 0.0296 | 0.0144 | pcm | 34 |
| 0.0217 | 0.0304 | 0.0150 | pcm | 35 |
| 0.0224 | 0.0313 | 0.0156 | pcm | 36 |
| 0.0224 | 0.0313 | 0.0156 | pcm | 37 |
| 0.0232 | 0.0321 | 0.0162 | pcm | 38 |
| 0.0246 | 0.0338 | 0.0174 | pcm | 39 |
| 0.0246 | 0.0338 | 0.0174 | pcm | 40 |
| 0.0246 | 0.0338 | 0.0174 | pcm | 41 |
| 0.0261 | 0.0355 | 0.0186 | pcm | 42 |
| 0.0261 | 0.0355 | 0.0186 | pcm | 43 |
| 0.0268 | 0.0363 | 0.0192 | pcm | 44 |
| 0.0275 | 0.0371 | 0.0198 | pcm | 45 |
| 0.0275 | 0.0371 | 0.0198 | pcm | 46 |
| 0.0275 | 0.0371 | 0.0198 | pcm | 47 |
| 0.0275 | 0.0371 | 0.0198 | pcm | 48 |
| 0.0275 | 0.0371 | 0.0198 | pcm | 49 |
| 0.0275 | 0.0371 | 0.0198 | pcm | 50 |
| 0.0290 | 0.0388 | 0.0211 | pcm | 51 |
| 0.0304 | 0.0405 | 0.0223 | pcm | 52 |
| 0.0304 | 0.0405 | 0.0223 | pcm | 53 |
| 0.0304 | 0.0405 | 0.0223 | pcm | 54 |
| 0.0304 | 0.0405 | 0.0223 | pcm | 55 |
| 0.0311 | 0.0413 | 0.0229 | pcm | 56 |
| 0.0326 | 0.0430 | 0.0242 | pcm | 57 |
| 0.0326 | 0.0430 | 0.0242 | pcm | 58 |
| 0.0326 | 0.0430 | 0.0242 | pcm | 59 |
First 60 of 538 rows.
Assumptions
- Non-informative censoring — 409 of 1384 observations are censored (censored).
- Number of events — At least 10 events per cause.
Cumulative incidence at chosen times
| Curve | Cause | Time | Cumulative incidence | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| All | pcm | 60 | 0.0341 | 0.0254 | 0.0447 |
| All | pcm | 120 | 0.0637 | 0.0513 | 0.0779 |
| All | pcm | 240 | 0.0998 | 0.0817 | 0.1200 |
| All | pcm | 600 | — | — | — |
| All | death | 60 | 0.3204 | 0.2959 | 0.3451 |
| All | death | 120 | 0.5318 | 0.5039 | 0.5589 |
| All | death | 240 | 0.7240 | 0.6921 | 0.7533 |
| All | death | 600 | — | — | — |
Aalen–Johansen estimate; delta-method SE with a log–log interval.
- Censoring level: censored; causes: pcm, death. 1 − Kaplan–Meier would overstate incidence when competing events occur.
The exact R script · R R version 4.5.1 (2025-06-13)
# Cumulative incidence with competing risks
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cif 1.2.0 · spec 08bff24c812b789e
# Dataset: mgus2_cr (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(survival)
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mgus2_cr.parquet", col_select = c("etime", "event")))
n_input <- nrow(df)
df[["event"]] <- factor(df[["event"]], levels = c("censored", "pcm", "death")) # stored level order
df <- df[stats::complete.cases(df[c("etime", "event")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("etime", "event")) # infinite values stop the run (registry/errors.yaml)
# %% Event types
tcol <- "etime"
ecol <- "event"
tt <- as.numeric(df[[tcol]])
if (any(tt < 0)) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = "zero or positive (survival times)", count = sum(tt < 0))
ev_levels <- levels(df[[ecol]])
censor <- "censored"
if (!(censor %in% ev_levels)) cs_error("CS_E_NOT_A_LEVEL", level = censor, column = ecol) # the censoring level must occur in the data
causes <- setdiff(ev_levels, censor)
if (length(causes) == 0) cs_error("CS_E_NO_EVENTS", event = sprintf("%s other than %s", ecol, censor))
cause <- NULL
if (is.null(cause)) cause <- causes[1]
if (!(cause %in% causes)) cs_error("CS_E_NOT_A_LEVEL", level = cause, column = ecol)
ec <- as.character(df[[ecol]])
code <- ifelse(ec == censor, 0L, match(ec, causes))
conf <- 0.95
times <- c(60, 120, 240, 600)
if (length(times) == 0) times <- cs_default_times(tt)
levels_g <- character(0)
groups <- list(All = rep(TRUE, length(tt)))
# %% Cumulative incidence (Aalen–Johansen, survfit multi-state)
ci <- match(cause, causes)
values <- list(n = length(tt), n_censored = sum(code == 0), n_events = sum(code == ci),
n_competing = sum(code != 0 & code != ci), cause_label = cause, censor_label = censor,
n_causes = length(causes), n_groups = if (length(levels_g)) length(levels_g) else NA)
for (j in seq_along(causes)) values[[sprintf("events[%s]", causes[j])]] <- sum(code == j)
z <- stats::qnorm(1 - (1 - conf) / 2)
loglog <- function(F, se) {
Fx <- ifelse(F > 0 & F < 1, F, NA)
seg <- se / (Fx * abs(log(Fx)))
list(lower = Fx^exp(z * seg), upper = Fx^exp(-z * seg))
}
fin <- function(x) if (length(x) == 0 || !is.finite(x)) NA else unname(x)
rows <- list()
curve <- list(time = numeric(0), cif = numeric(0), low = numeric(0), high = numeric(0), strata = character(0))
for (name in names(groups)) {
m <- groups[[name]]
st <- factor(ec[m], levels = c(censor, causes))
fit <- survfit(Surv(tt[m], st) ~ 1)
for (j in seq_along(causes)) {
col <- match(causes[j], fit$states)
F <- if (is.na(col)) rep(0, length(fit$time)) else fit$pstate[, col]
se <- if (is.na(col)) rep(0, length(fit$time)) else fit$std.err[, col]
lim <- loglog(F, se)
f_at <- cs_step_at(fit$time, F, times, start = 0)
l_at <- cs_step_at(fit$time, lim$lower, times, start = NA)
u_at <- cs_step_at(fit$time, lim$upper, times, start = NA)
for (i in seq_along(times)) {
key <- sprintf("%s·%s@%s", name, causes[j], cs_key_num(times[i]))
values[[sprintf("cif[%s]", key)]] <- fin(f_at[i])
values[[sprintf("cif_low[%s]", key)]] <- fin(l_at[i])
values[[sprintf("cif_high[%s]", key)]] <- fin(u_at[i])
rows[[length(rows) + 1]] <- list(group = name, cause = causes[j], time = times[i], cif = fin(f_at[i]),
lower = fin(l_at[i]), upper = fin(u_at[i]))
}
if ((name == "All") == (length(levels_g) == 0)) {
label <- if (length(levels_g)) sprintf("%s · %s", name, causes[j]) else causes[j]
curve$time <- c(curve$time, 0, fit$time)
curve$cif <- c(curve$cif, 0, F)
curve$low <- c(curve$low, NA, lim$lower)
curve$high <- c(curve$high, NA, lim$upper)
curve$strata <- c(curve$strata, rep(label, length(fit$time) + 1))
}
}
}
# %% Group comparisons: Gray's test of the curves, cause-specific log-rank tests of the rates
test_kind <- "gray"
gray_rho <- 0 # Gray's weight (1 - F(t-))^rho; 0 is cuminc's default
test_label <- if (test_kind == "gray") "Gray's test" else "cause-specific log-rank"
values$test_kind <- test_kind
values$test_label <- test_label
test_rows <- list()
if (length(levels_g)) {
gf <- factor(gv, levels = levels_g)
gray <- cmprsk::cuminc(tt, ec, gf, cencode = censor, rho = gray_rho)$Tests
for (j in seq_along(causes)) {
r <- survdiff(Surv(tt, code == j) ~ gf)
dfree <- sum(r$n > 0) - 1
pj <- stats::pchisq(r$chisq, dfree, lower.tail = FALSE)
gr <- gray[causes[j], ]
values[[sprintf("chisq_cause[%s]", causes[j])]] <- r$chisq
values[[sprintf("p_cause[%s]", causes[j])]] <- pj
values[[sprintf("gray_chisq[%s]", causes[j])]] <- unname(gr["stat"])
values[[sprintf("gray_p[%s]", causes[j])]] <- unname(gr["pv"])
test_rows[[j]] <- list(cause = causes[j], gray = unname(gr["stat"]), gray_df = unname(gr["df"]), gray_p = unname(gr["pv"]), chisq = r$chisq, df = dfree, p = pj)
if (causes[j] == cause) {
if (test_kind == "gray") {
values$chisq <- unname(gr["stat"])
values$df <- unname(gr["df"])
values$p <- unname(gr["pv"])
} else {
values$chisq <- r$chisq
values$df <- dfree
values$p <- pj
}
}
}
} else {
values$chisq <- NA
values$df <- NA
values$p <- NA
}
# %% Assumptions
few <- causes[vapply(causes, function(cc) values[[sprintf("events[%s]", cc)]] < 10, logical(1))]
assumptions <- list(
list(key = "censoring", label = "Non-informative censoring", status = "info",
detail = sprintf("%d of %d observations are censored (%s).", values$n_censored, length(tt), censor)),
list(key = "sample_size", label = "Number of events", status = if (length(few)) "warn" else "pass",
detail = if (length(few)) sprintf("Fewer than 10 events for %s.", paste(few, collapse = ", ")) else "At least 10 events per cause.")
)
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
strata_levels <- if (length(levels_g)) as.vector(t(outer(levels_g, causes, paste, sep = " · "))) else causes
tables <- list(list(key = "incidence", title = "Cumulative incidence at chosen times", columns = list(
list(key = "group", label = if (length(levels_g)) g else "Curve", type = "string"), list(key = "cause", label = "Cause", type = "string"),
list(key = "time", label = "Time", type = "number"), list(key = "cif", label = "Cumulative incidence", type = "number"),
list(key = "lower", label = paste(pct, "CI low"), type = "number"), list(key = "upper", label = paste(pct, "CI high"), type = "number")
), rows = rows, note = "Aalen–Johansen estimate; delta-method SE with a log–log interval."))
if (length(test_rows)) {
tables[[2]] <- list(key = "tests", title = "Group comparisons by cause", columns = list(
list(key = "cause", label = "Cause", type = "string"), list(key = "gray", label = "Gray's χ²", type = "number"),
list(key = "gray_df", label = "df", type = "integer"), list(key = "gray_p", label = "Gray's p", type = "pvalue"),
list(key = "chisq", label = "Log-rank χ²", type = "number"), list(key = "df", label = "df", type = "integer"), list(key = "p", label = "Log-rank p", type = "pvalue")
), rows = test_rows, note = "Gray's test compares the cumulative incidence curves; the cause-specific log-rank test compares the event rates among those still at risk.")
}
cs_publish(list(
method = "survival.cif",
methodVersion = "1.2.0",
title = paste0("Cumulative incidence (competing risks)", if (length(levels_g)) paste(" by", g) else ""),
engine = cs_engine_info("survival", "codesplashr"),
n = length(tt),
summary = paste0(sprintf("%d %s events, %d competing events, %d censored.", values$n_events, cause, values$n_competing, values$n_censored),
if (length(levels_g)) sprintf(" %s for %s: %s.", if (test_kind == "gray") test_label else "Cause-specific log-rank", cause, cs_fmt_p(values$p)) else ""),
apa = if (length(levels_g)) sprintf("χ²(%d) = %s, %s", values$df, cs_fmt_num(values$chisq), cs_fmt_p(values$p))
else sprintf("%d events of interest, N = %d", values$n_events, length(tt)),
statistics = c(list(list(key = "n_events", label = paste(cause, "events"), value = values$n_events, format = "integer"),
list(key = "n_competing", label = "Competing events", value = values$n_competing, format = "integer")),
if (length(levels_g)) list(list(key = "p", label = paste(test_label, "p"), value = values$p, format = "p"))),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Censoring level: %s; causes: %s. 1 − Kaplan–Meier would overstate incidence when competing events occur.",
censor, paste(causes, collapse = ", "))),
charts = list(cs_chart("cif", "cif-curve", paste0("Cumulative incidence", if (length(levels_g)) paste(" by", g) else ""), list(
time = cs_col(tcol, curve$time, "numeric"), cif = cs_col("Cumulative incidence", curve$cif, "numeric"),
low = cs_col("lower", curve$low, "numeric"), high = cs_col("upper", curve$high, "numeric"),
strata = cs_col("Curve", curve$strata, "categorical", levels = strata_levels)
))),
values = values
))
115 events of interest, N = 1384
- pcm events
- 115
- Competing events
- 860
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Non-informative censoring — 409 of 1384 observations are censored (censored).
- Number of events — At least 10 events per cause.
Cumulative incidence at chosen times
| Curve | Cause | Time | Cumulative incidence | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| All | pcm | 60 | 0.0341 | 0.0254 | 0.0447 |
| All | pcm | 120 | 0.0637 | 0.0513 | 0.0779 |
| All | pcm | 240 | 0.0998 | 0.0817 | 0.1200 |
| All | pcm | 600 | — | — | — |
| All | death | 60 | 0.3204 | 0.2959 | 0.3451 |
| All | death | 120 | 0.5318 | 0.5039 | 0.5589 |
| All | death | 240 | 0.7240 | 0.6921 | 0.7533 |
| All | death | 600 | — | — | — |
Aalen–Johansen estimate; delta-method SE with a log–log interval.
- Censoring level: censored; causes: pcm, death. 1 − Kaplan–Meier would overstate incidence when competing events occur.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Cumulative incidence with competing risks
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cif 1.2.0 · spec 08bff24c812b789e
# Dataset: mgus2_cr (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import survival as sv # Aalen–Johansen (survfit multi-state) and survdiff twins
from codesplash.stats import survival_adv as sa # Gray's test
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mgus2_cr.parquet", columns=["etime", "event"])
n_input = len(df)
df["event"] = pd.Categorical(df["event"], categories=["censored", "pcm", "death"]) # stored level order
df = df.dropna(subset=["etime", "event"]) # listwise deletion over the analysis columns
df["event"] = df["event"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["etime", "event"]) # infinite values stop the run (registry/errors.yaml)
# %% Event types
tcol = "etime"
ecol = "event"
t = df[tcol].to_numpy(dtype=float)
if (t < 0).any():
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement="zero or positive (survival times)", count=int((t < 0).sum()))
ev_levels = [str(x) for x in df[ecol].cat.categories]
censor = "censored"
if censor not in ev_levels:
cs.cs_error("CS_E_NOT_A_LEVEL", level=censor, column=ecol) # the censoring level must occur in the data
causes = [lv for lv in ev_levels if lv != censor]
if not causes:
cs.cs_error("CS_E_NO_EVENTS", event=f"{ecol} other than {censor}")
cause = None or causes[0]
if cause not in causes:
cs.cs_error("CS_E_NOT_A_LEVEL", level=cause, column=ecol)
ec = df[ecol].astype(str).to_numpy()
code = np.array([0 if x == censor else causes.index(x) + 1 for x in ec])
conf = 0.95
times = [60, 120, 240, 600, ] or sv.default_times(t)
levels = []
groups = [("All", np.ones(len(t), dtype=bool))]
# %% Cumulative incidence (Aalen–Johansen)
ci = causes.index(cause) + 1
values = {"n": float(len(t)), "n_censored": float((code == 0).sum()), "n_events": float((code == ci).sum()),
"n_competing": float(((code != 0) & (code != ci)).sum()), "cause_label": cause, "censor_label": censor,
"n_causes": float(len(causes)), "n_groups": float(len(levels)) if levels else None}
for j, c in enumerate(causes):
values[f"events[{c}]"] = float((code == j + 1).sum())
nan = lambda x: None if x is None or not np.isfinite(x) else float(x) # noqa: E731
rows = []
curve = {"time": [], "cif": [], "low": [], "high": [], "strata": []}
for name, m in groups:
res = sv.cif(t[m], code[m], len(causes), conf=conf)
i = np.searchsorted(res["time"], np.asarray(times, dtype=float), side="right") - 1
for j, c in enumerate(causes):
for x, ii in zip(times, i):
beyond = x > res["time"][-1]
f = None if beyond else (0.0 if ii < 0 else nan(res["cif"][j, ii]))
lo = None if beyond or ii < 0 else nan(res["lower"][j, ii])
hi = None if beyond or ii < 0 else nan(res["upper"][j, ii])
key = f"{name}·{c}@{sv.key_num(x)}"
values[f"cif[{key}]"], values[f"cif_low[{key}]"], values[f"cif_high[{key}]"] = f, lo, hi
rows.append({"group": name, "cause": c, "time": x, "cif": f, "lower": lo, "upper": hi})
if (name == "All") == (not levels):
label = c if not levels else f"{name} · {c}"
curve["time"] += [0.0] + res["time"].tolist()
curve["cif"] += [0.0] + res["cif"][j].tolist()
curve["low"] += [None] + [nan(x) for x in res["lower"][j]]
curve["high"] += [None] + [nan(x) for x in res["upper"][j]]
curve["strata"] += [label] * (len(res["time"]) + 1)
# %% Group comparisons: Gray's test of the curves, cause-specific log-rank tests of the rates
test_kind = "gray"
gray_rho = 0 # Gray's weight (1 − F̂(t−))^ρ; 0 is cuminc's default
test_label = "Gray's test" if test_kind == "gray" else "cause-specific log-rank"
values.update({"test_kind": test_kind, "test_label": test_label})
test_rows = []
if levels:
gcodes = np.array([levels.index(x) for x in gv])
for j, c in enumerate(causes):
r = sv.logrank(t, code == j + 1, gcodes)
gr = sa.gray_test(t, np.where(code == j + 1, 1, np.where(code == 0, 0, 2)), gcodes, rho=gray_rho)
values[f"chisq_cause[{c}]"], values[f"p_cause[{c}]"] = r["chisq"], r["p"]
values[f"gray_chisq[{c}]"], values[f"gray_p[{c}]"] = gr["chisq"], gr["p"]
test_rows.append({"cause": c, "gray": gr["chisq"], "gray_df": float(gr["df"]), "gray_p": gr["p"], "chisq": r["chisq"], "df": float(r["df"]), "p": r["p"]})
if c == cause:
if test_kind == "gray":
values.update({"chisq": gr["chisq"], "df": float(gr["df"]), "p": gr["p"]})
else:
values.update({"chisq": r["chisq"], "df": float(r["df"]), "p": r["p"]})
else:
values.update({"chisq": None, "df": None, "p": None})
# %% Assumptions
few = [c for c in causes if values[f"events[{c}]"] < 10]
assumptions = [{"key": "censoring", "label": "Non-informative censoring", "status": "info",
"detail": f"{int(values['n_censored'])} of {len(t)} observations are censored ({censor})."},
{"key": "sample_size", "label": "Number of events", "status": "warn" if few else "pass",
"detail": f"Fewer than 10 events for {', '.join(few)}." if few else "At least 10 events per cause."}]
# %% Result
pct = f"{conf:.0%}"
strata_levels = causes if not levels else [f"{lv} · {c}" for lv in levels for c in causes]
tables = [{"key": "incidence", "title": "Cumulative incidence at chosen times", "columns": [
{"key": "group", "label": g if levels else "Curve", "type": "string"}, {"key": "cause", "label": "Cause", "type": "string"},
{"key": "time", "label": "Time", "type": "number"}, {"key": "cif", "label": "Cumulative incidence", "type": "number"},
{"key": "lower", "label": f"{pct} CI low", "type": "number"}, {"key": "upper", "label": f"{pct} CI high", "type": "number"},
], "rows": rows, "note": "Aalen–Johansen estimate; delta-method SE with a log–log interval."}]
if test_rows:
tables.append({"key": "tests", "title": "Group comparisons by cause", "columns": [
{"key": "cause", "label": "Cause", "type": "string"}, {"key": "gray", "label": "Gray's χ²", "type": "number"},
{"key": "gray_df", "label": "df", "type": "integer"}, {"key": "gray_p", "label": "Gray's p", "type": "pvalue"},
{"key": "chisq", "label": "Log-rank χ²", "type": "number"}, {"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "Log-rank p", "type": "pvalue"},
], "rows": test_rows, "note": "Gray's test compares the cumulative incidence curves; the cause-specific log-rank test compares the event rates among those still at risk."})
cs.publish({
"method": "survival.cif",
"methodVersion": "1.2.0",
"title": "Cumulative incidence (competing risks)" + (f" by {g}" if levels else ""),
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(len(t)),
"summary": f"{int(values['n_events'])} {cause} events, {int(values['n_competing'])} competing events, {int(values['n_censored'])} censored."
+ (f" {test_label.capitalize() if test_kind != 'gray' else test_label} for {cause}: {cs.fmt_p(values['p'])}." if levels else ""),
"apa": (f"χ²({values['df']:.0f}) = {cs.fmt_num(values['chisq'])}, {cs.fmt_p(values['p'])}" if levels
else f"{int(values['n_events'])} events of interest, N = {len(t)}"),
"statistics": [{"key": "n_events", "label": f"{cause} events", "value": values["n_events"], "format": "integer"},
{"key": "n_competing", "label": "Competing events", "value": values["n_competing"], "format": "integer"}]
+ ([{"key": "p", "label": f"{test_label} p", "value": values["p"], "format": "p"}] if levels else []),
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Censoring level: {censor}; causes: {', '.join(causes)}. 1 − Kaplan–Meier would overstate incidence when competing events occur."],
"charts": [cs.chart("cif", "cif-curve", "Cumulative incidence" + (f" by {g}" if levels else ""), {
"time": cs.col(tcol, curve["time"], "numeric"), "cif": cs.col("Cumulative incidence", curve["cif"], "numeric"),
"low": cs.col("lower", curve["low"], "numeric"), "high": cs.col("upper", curve["high"], "numeric"),
"strata": cs.col("Curve", curve["strata"], "categorical", levels=strata_levels),
})],
"values": values,
})
Compare the two for yourself
Readimport pandas as pd
from lifelines import AalenJohansenFitter, KaplanMeierFitter
m = pd.read_csv("mgus2_cr.csv")
codes = m["event"].map({"censored": 0, "pcm": 1, "death": 2})
aj = AalenJohansenFitter(calculate_variance=False, seed=1).fit(m["etime"], codes, event_of_interest=1)
print("cumulative incidence at 240:", aj.cumulative_density_.loc[:240].iloc[-1, 0])
km = KaplanMeierFitter().fit(m["etime"], event_observed=codes == 1)
print("1 - KM at 240:", 1 - km.predict(240))library(survival)
m <- read.csv("mgus2_cr.csv")
m$event <- factor(m$event, levels = c("censored", "pcm", "death"))
aj <- survfit(Surv(etime, event) ~ 1, data = m)
summary(aj, times = 240)$pstate # event-free, pcm, death
km <- survfit(Surv(etime, event == "pcm") ~ 1, data = m)
1 - summary(km, times = 240)$survGray's test
In the appTo compare cumulative incidence between groups, the log-rank test is the wrong tool. Gray's testGray's testCompares cumulative incidence curves between groups under competing risks; it asks how many events each group ends up with. compares the cumulative incidence curves of one cause, keeping those with a competing event in the risk set.
For death by sex: = 11.65, p < .001.
χ²(1) = 11.65, p < .001
- death events
- 860
- Competing events
- 115
- Gray's test p
- < .001
Assumptions
- Non-informative censoring — 409 of 1384 observations are censored (censored).
- Number of events — At least 10 events per cause.
Cumulative incidence at chosen times
| sex | Cause | Time | Cumulative incidence | 90% CI low | 90% CI high |
|---|---|---|---|---|---|
| All | pcm | 110 | 0.0600 | 0.0498 | 0.0714 |
| All | pcm | 210 | 0.0938 | 0.0798 | 0.1091 |
| All | pcm | 320 | 0.1177 | 0.0958 | 0.1420 |
| All | death | 110 | 0.5045 | 0.4814 | 0.5272 |
| All | death | 210 | 0.6927 | 0.6679 | 0.7161 |
| All | death | 320 | 0.7719 | 0.7391 | 0.8012 |
| F | pcm | 110 | 0.0657 | 0.0505 | 0.0836 |
| F | pcm | 210 | 0.0992 | 0.0789 | 0.1222 |
| F | pcm | 320 | 0.1299 | 0.0966 | 0.1684 |
| F | death | 110 | 0.4537 | 0.4197 | 0.4871 |
| F | death | 210 | 0.6623 | 0.6243 | 0.6974 |
| F | death | 320 | 0.7383 | 0.6880 | 0.7818 |
| M | pcm | 110 | 0.0553 | 0.0423 | 0.0707 |
| M | pcm | 210 | 0.0891 | 0.0706 | 0.1102 |
| M | pcm | 320 | 0.1045 | 0.0803 | 0.1322 |
| M | death | 110 | 0.5474 | 0.5158 | 0.5779 |
| M | death | 210 | 0.7189 | 0.6854 | 0.7494 |
| M | death | 320 | 0.7994 | 0.7569 | 0.8353 |
Aalen–Johansen estimate; delta-method SE with a log–log interval.
Group comparisons by cause
| Cause | Gray's χ² | df | Gray's p | Log-rank χ² | df | Log-rank p |
|---|---|---|---|---|---|---|
| pcm | 1.195 | 1 | .274 | 0.1006 | 1 | .751 |
| death | 11.651 | 1 | < .001 | 10.986 | 1 | < .001 |
Gray's test compares the cumulative incidence curves; the cause-specific log-rank test compares the event rates among those still at risk.
- Censoring level: censored; causes: pcm, death. 1 − Kaplan–Meier would overstate incidence when competing events occur.
The exact R script · R R version 4.5.1 (2025-06-13)
# Cumulative incidence with competing risks
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cif 1.2.0 · spec 64fe6af720a45bc8
# Dataset: mgus2_cr (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(survival)
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mgus2_cr.parquet", col_select = c("etime", "event", "sex")))
n_input <- nrow(df)
df[["event"]] <- factor(df[["event"]], levels = c("censored", "pcm", "death")) # stored level order
df[["sex"]] <- factor(df[["sex"]], levels = c("F", "M")) # stored level order
df <- df[stats::complete.cases(df[c("etime", "event", "sex")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("etime", "event", "sex")) # infinite values stop the run (registry/errors.yaml)
# %% Event types
tcol <- "etime"
ecol <- "event"
tt <- as.numeric(df[[tcol]])
if (any(tt < 0)) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = "zero or positive (survival times)", count = sum(tt < 0))
ev_levels <- levels(df[[ecol]])
censor <- "censored"
if (!(censor %in% ev_levels)) cs_error("CS_E_NOT_A_LEVEL", level = censor, column = ecol) # the censoring level must occur in the data
causes <- setdiff(ev_levels, censor)
if (length(causes) == 0) cs_error("CS_E_NO_EVENTS", event = sprintf("%s other than %s", ecol, censor))
cause <- "death"
if (is.null(cause)) cause <- causes[1]
if (!(cause %in% causes)) cs_error("CS_E_NOT_A_LEVEL", level = cause, column = ecol)
ec <- as.character(df[[ecol]])
code <- ifelse(ec == censor, 0L, match(ec, causes))
conf <- 0.9
times <- c()
if (length(times) == 0) times <- cs_default_times(tt)
g <- "sex"
levels_g <- levels(df[[g]])
gv <- as.character(df[[g]])
groups <- c(list(All = rep(TRUE, length(tt))), stats::setNames(lapply(levels_g, function(lv) gv == lv), levels_g))
# %% Cumulative incidence (Aalen–Johansen, survfit multi-state)
ci <- match(cause, causes)
values <- list(n = length(tt), n_censored = sum(code == 0), n_events = sum(code == ci),
n_competing = sum(code != 0 & code != ci), cause_label = cause, censor_label = censor,
n_causes = length(causes), n_groups = if (length(levels_g)) length(levels_g) else NA)
for (j in seq_along(causes)) values[[sprintf("events[%s]", causes[j])]] <- sum(code == j)
z <- stats::qnorm(1 - (1 - conf) / 2)
loglog <- function(F, se) {
Fx <- ifelse(F > 0 & F < 1, F, NA)
seg <- se / (Fx * abs(log(Fx)))
list(lower = Fx^exp(z * seg), upper = Fx^exp(-z * seg))
}
fin <- function(x) if (length(x) == 0 || !is.finite(x)) NA else unname(x)
rows <- list()
curve <- list(time = numeric(0), cif = numeric(0), low = numeric(0), high = numeric(0), strata = character(0))
for (name in names(groups)) {
m <- groups[[name]]
st <- factor(ec[m], levels = c(censor, causes))
fit <- survfit(Surv(tt[m], st) ~ 1)
for (j in seq_along(causes)) {
col <- match(causes[j], fit$states)
F <- if (is.na(col)) rep(0, length(fit$time)) else fit$pstate[, col]
se <- if (is.na(col)) rep(0, length(fit$time)) else fit$std.err[, col]
lim <- loglog(F, se)
f_at <- cs_step_at(fit$time, F, times, start = 0)
l_at <- cs_step_at(fit$time, lim$lower, times, start = NA)
u_at <- cs_step_at(fit$time, lim$upper, times, start = NA)
for (i in seq_along(times)) {
key <- sprintf("%s·%s@%s", name, causes[j], cs_key_num(times[i]))
values[[sprintf("cif[%s]", key)]] <- fin(f_at[i])
values[[sprintf("cif_low[%s]", key)]] <- fin(l_at[i])
values[[sprintf("cif_high[%s]", key)]] <- fin(u_at[i])
rows[[length(rows) + 1]] <- list(group = name, cause = causes[j], time = times[i], cif = fin(f_at[i]),
lower = fin(l_at[i]), upper = fin(u_at[i]))
}
if ((name == "All") == (length(levels_g) == 0)) {
label <- if (length(levels_g)) sprintf("%s · %s", name, causes[j]) else causes[j]
curve$time <- c(curve$time, 0, fit$time)
curve$cif <- c(curve$cif, 0, F)
curve$low <- c(curve$low, NA, lim$lower)
curve$high <- c(curve$high, NA, lim$upper)
curve$strata <- c(curve$strata, rep(label, length(fit$time) + 1))
}
}
}
# %% Group comparisons: Gray's test of the curves, cause-specific log-rank tests of the rates
test_kind <- "gray"
gray_rho <- 0 # Gray's weight (1 - F(t-))^rho; 0 is cuminc's default
test_label <- if (test_kind == "gray") "Gray's test" else "cause-specific log-rank"
values$test_kind <- test_kind
values$test_label <- test_label
test_rows <- list()
if (length(levels_g)) {
gf <- factor(gv, levels = levels_g)
gray <- cmprsk::cuminc(tt, ec, gf, cencode = censor, rho = gray_rho)$Tests
for (j in seq_along(causes)) {
r <- survdiff(Surv(tt, code == j) ~ gf)
dfree <- sum(r$n > 0) - 1
pj <- stats::pchisq(r$chisq, dfree, lower.tail = FALSE)
gr <- gray[causes[j], ]
values[[sprintf("chisq_cause[%s]", causes[j])]] <- r$chisq
values[[sprintf("p_cause[%s]", causes[j])]] <- pj
values[[sprintf("gray_chisq[%s]", causes[j])]] <- unname(gr["stat"])
values[[sprintf("gray_p[%s]", causes[j])]] <- unname(gr["pv"])
test_rows[[j]] <- list(cause = causes[j], gray = unname(gr["stat"]), gray_df = unname(gr["df"]), gray_p = unname(gr["pv"]), chisq = r$chisq, df = dfree, p = pj)
if (causes[j] == cause) {
if (test_kind == "gray") {
values$chisq <- unname(gr["stat"])
values$df <- unname(gr["df"])
values$p <- unname(gr["pv"])
} else {
values$chisq <- r$chisq
values$df <- dfree
values$p <- pj
}
}
}
} else {
values$chisq <- NA
values$df <- NA
values$p <- NA
}
# %% Assumptions
few <- causes[vapply(causes, function(cc) values[[sprintf("events[%s]", cc)]] < 10, logical(1))]
assumptions <- list(
list(key = "censoring", label = "Non-informative censoring", status = "info",
detail = sprintf("%d of %d observations are censored (%s).", values$n_censored, length(tt), censor)),
list(key = "sample_size", label = "Number of events", status = if (length(few)) "warn" else "pass",
detail = if (length(few)) sprintf("Fewer than 10 events for %s.", paste(few, collapse = ", ")) else "At least 10 events per cause.")
)
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
strata_levels <- if (length(levels_g)) as.vector(t(outer(levels_g, causes, paste, sep = " · "))) else causes
tables <- list(list(key = "incidence", title = "Cumulative incidence at chosen times", columns = list(
list(key = "group", label = if (length(levels_g)) g else "Curve", type = "string"), list(key = "cause", label = "Cause", type = "string"),
list(key = "time", label = "Time", type = "number"), list(key = "cif", label = "Cumulative incidence", type = "number"),
list(key = "lower", label = paste(pct, "CI low"), type = "number"), list(key = "upper", label = paste(pct, "CI high"), type = "number")
), rows = rows, note = "Aalen–Johansen estimate; delta-method SE with a log–log interval."))
if (length(test_rows)) {
tables[[2]] <- list(key = "tests", title = "Group comparisons by cause", columns = list(
list(key = "cause", label = "Cause", type = "string"), list(key = "gray", label = "Gray's χ²", type = "number"),
list(key = "gray_df", label = "df", type = "integer"), list(key = "gray_p", label = "Gray's p", type = "pvalue"),
list(key = "chisq", label = "Log-rank χ²", type = "number"), list(key = "df", label = "df", type = "integer"), list(key = "p", label = "Log-rank p", type = "pvalue")
), rows = test_rows, note = "Gray's test compares the cumulative incidence curves; the cause-specific log-rank test compares the event rates among those still at risk.")
}
cs_publish(list(
method = "survival.cif",
methodVersion = "1.2.0",
title = paste0("Cumulative incidence (competing risks)", if (length(levels_g)) paste(" by", g) else ""),
engine = cs_engine_info("survival", "codesplashr"),
n = length(tt),
summary = paste0(sprintf("%d %s events, %d competing events, %d censored.", values$n_events, cause, values$n_competing, values$n_censored),
if (length(levels_g)) sprintf(" %s for %s: %s.", if (test_kind == "gray") test_label else "Cause-specific log-rank", cause, cs_fmt_p(values$p)) else ""),
apa = if (length(levels_g)) sprintf("χ²(%d) = %s, %s", values$df, cs_fmt_num(values$chisq), cs_fmt_p(values$p))
else sprintf("%d events of interest, N = %d", values$n_events, length(tt)),
statistics = c(list(list(key = "n_events", label = paste(cause, "events"), value = values$n_events, format = "integer"),
list(key = "n_competing", label = "Competing events", value = values$n_competing, format = "integer")),
if (length(levels_g)) list(list(key = "p", label = paste(test_label, "p"), value = values$p, format = "p"))),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Censoring level: %s; causes: %s. 1 − Kaplan–Meier would overstate incidence when competing events occur.",
censor, paste(causes, collapse = ", "))),
charts = list(cs_chart("cif", "cif-curve", paste0("Cumulative incidence", if (length(levels_g)) paste(" by", g) else ""), list(
time = cs_col(tcol, curve$time, "numeric"), cif = cs_col("Cumulative incidence", curve$cif, "numeric"),
low = cs_col("lower", curve$low, "numeric"), high = cs_col("upper", curve$high, "numeric"),
strata = cs_col("Curve", curve$strata, "categorical", levels = strata_levels)
))),
values = values
))
χ²(1) = 11.65, p < .001
- death events
- 860
- Competing events
- 115
- Gray's test p
- < .001
Assumptions
- Non-informative censoring — 409 of 1384 observations are censored (censored).
- Number of events — At least 10 events per cause.
Cumulative incidence at chosen times
| sex | Cause | Time | Cumulative incidence | 90% CI low | 90% CI high |
|---|---|---|---|---|---|
| All | pcm | 110 | 0.0600 | 0.0498 | 0.0714 |
| All | pcm | 210 | 0.0938 | 0.0798 | 0.1091 |
| All | pcm | 320 | 0.1177 | 0.0958 | 0.1420 |
| All | death | 110 | 0.5045 | 0.4814 | 0.5272 |
| All | death | 210 | 0.6927 | 0.6679 | 0.7161 |
| All | death | 320 | 0.7719 | 0.7391 | 0.8012 |
| F | pcm | 110 | 0.0657 | 0.0505 | 0.0836 |
| F | pcm | 210 | 0.0992 | 0.0789 | 0.1222 |
| F | pcm | 320 | 0.1299 | 0.0966 | 0.1684 |
| F | death | 110 | 0.4537 | 0.4197 | 0.4871 |
| F | death | 210 | 0.6623 | 0.6243 | 0.6974 |
| F | death | 320 | 0.7383 | 0.6880 | 0.7818 |
| M | pcm | 110 | 0.0553 | 0.0423 | 0.0707 |
| M | pcm | 210 | 0.0891 | 0.0706 | 0.1102 |
| M | pcm | 320 | 0.1045 | 0.0803 | 0.1322 |
| M | death | 110 | 0.5474 | 0.5158 | 0.5779 |
| M | death | 210 | 0.7189 | 0.6854 | 0.7494 |
| M | death | 320 | 0.7994 | 0.7569 | 0.8353 |
Aalen–Johansen estimate; delta-method SE with a log–log interval.
Group comparisons by cause
| Cause | Gray's χ² | df | Gray's p | Log-rank χ² | df | Log-rank p |
|---|---|---|---|---|---|---|
| pcm | 1.195 | 1 | .274 | 0.1006 | 1 | .751 |
| death | 11.651 | 1 | < .001 | 10.986 | 1 | < .001 |
Gray's test compares the cumulative incidence curves; the cause-specific log-rank test compares the event rates among those still at risk.
- Censoring level: censored; causes: pcm, death. 1 − Kaplan–Meier would overstate incidence when competing events occur.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Cumulative incidence with competing risks
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cif 1.2.0 · spec 64fe6af720a45bc8
# Dataset: mgus2_cr (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import survival as sv # Aalen–Johansen (survfit multi-state) and survdiff twins
from codesplash.stats import survival_adv as sa # Gray's test
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mgus2_cr.parquet", columns=["etime", "event", "sex"])
n_input = len(df)
df["event"] = pd.Categorical(df["event"], categories=["censored", "pcm", "death"]) # stored level order
df["sex"] = pd.Categorical(df["sex"], categories=["F", "M"]) # stored level order
df = df.dropna(subset=["etime", "event", "sex"]) # listwise deletion over the analysis columns
df["event"] = df["event"].cat.remove_unused_categories()
df["sex"] = df["sex"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["etime", "event", "sex"]) # infinite values stop the run (registry/errors.yaml)
# %% Event types
tcol = "etime"
ecol = "event"
t = df[tcol].to_numpy(dtype=float)
if (t < 0).any():
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement="zero or positive (survival times)", count=int((t < 0).sum()))
ev_levels = [str(x) for x in df[ecol].cat.categories]
censor = "censored"
if censor not in ev_levels:
cs.cs_error("CS_E_NOT_A_LEVEL", level=censor, column=ecol) # the censoring level must occur in the data
causes = [lv for lv in ev_levels if lv != censor]
if not causes:
cs.cs_error("CS_E_NO_EVENTS", event=f"{ecol} other than {censor}")
cause = "death" or causes[0]
if cause not in causes:
cs.cs_error("CS_E_NOT_A_LEVEL", level=cause, column=ecol)
ec = df[ecol].astype(str).to_numpy()
code = np.array([0 if x == censor else causes.index(x) + 1 for x in ec])
conf = 0.9
times = [] or sv.default_times(t)
g = "sex"
levels = [str(x) for x in df[g].cat.categories]
gv = df[g].astype(str).to_numpy()
groups = [("All", np.ones(len(t), dtype=bool))] + [(lv, gv == lv) for lv in levels]
# %% Cumulative incidence (Aalen–Johansen)
ci = causes.index(cause) + 1
values = {"n": float(len(t)), "n_censored": float((code == 0).sum()), "n_events": float((code == ci).sum()),
"n_competing": float(((code != 0) & (code != ci)).sum()), "cause_label": cause, "censor_label": censor,
"n_causes": float(len(causes)), "n_groups": float(len(levels)) if levels else None}
for j, c in enumerate(causes):
values[f"events[{c}]"] = float((code == j + 1).sum())
nan = lambda x: None if x is None or not np.isfinite(x) else float(x) # noqa: E731
rows = []
curve = {"time": [], "cif": [], "low": [], "high": [], "strata": []}
for name, m in groups:
res = sv.cif(t[m], code[m], len(causes), conf=conf)
i = np.searchsorted(res["time"], np.asarray(times, dtype=float), side="right") - 1
for j, c in enumerate(causes):
for x, ii in zip(times, i):
beyond = x > res["time"][-1]
f = None if beyond else (0.0 if ii < 0 else nan(res["cif"][j, ii]))
lo = None if beyond or ii < 0 else nan(res["lower"][j, ii])
hi = None if beyond or ii < 0 else nan(res["upper"][j, ii])
key = f"{name}·{c}@{sv.key_num(x)}"
values[f"cif[{key}]"], values[f"cif_low[{key}]"], values[f"cif_high[{key}]"] = f, lo, hi
rows.append({"group": name, "cause": c, "time": x, "cif": f, "lower": lo, "upper": hi})
if (name == "All") == (not levels):
label = c if not levels else f"{name} · {c}"
curve["time"] += [0.0] + res["time"].tolist()
curve["cif"] += [0.0] + res["cif"][j].tolist()
curve["low"] += [None] + [nan(x) for x in res["lower"][j]]
curve["high"] += [None] + [nan(x) for x in res["upper"][j]]
curve["strata"] += [label] * (len(res["time"]) + 1)
# %% Group comparisons: Gray's test of the curves, cause-specific log-rank tests of the rates
test_kind = "gray"
gray_rho = 0 # Gray's weight (1 − F̂(t−))^ρ; 0 is cuminc's default
test_label = "Gray's test" if test_kind == "gray" else "cause-specific log-rank"
values.update({"test_kind": test_kind, "test_label": test_label})
test_rows = []
if levels:
gcodes = np.array([levels.index(x) for x in gv])
for j, c in enumerate(causes):
r = sv.logrank(t, code == j + 1, gcodes)
gr = sa.gray_test(t, np.where(code == j + 1, 1, np.where(code == 0, 0, 2)), gcodes, rho=gray_rho)
values[f"chisq_cause[{c}]"], values[f"p_cause[{c}]"] = r["chisq"], r["p"]
values[f"gray_chisq[{c}]"], values[f"gray_p[{c}]"] = gr["chisq"], gr["p"]
test_rows.append({"cause": c, "gray": gr["chisq"], "gray_df": float(gr["df"]), "gray_p": gr["p"], "chisq": r["chisq"], "df": float(r["df"]), "p": r["p"]})
if c == cause:
if test_kind == "gray":
values.update({"chisq": gr["chisq"], "df": float(gr["df"]), "p": gr["p"]})
else:
values.update({"chisq": r["chisq"], "df": float(r["df"]), "p": r["p"]})
else:
values.update({"chisq": None, "df": None, "p": None})
# %% Assumptions
few = [c for c in causes if values[f"events[{c}]"] < 10]
assumptions = [{"key": "censoring", "label": "Non-informative censoring", "status": "info",
"detail": f"{int(values['n_censored'])} of {len(t)} observations are censored ({censor})."},
{"key": "sample_size", "label": "Number of events", "status": "warn" if few else "pass",
"detail": f"Fewer than 10 events for {', '.join(few)}." if few else "At least 10 events per cause."}]
# %% Result
pct = f"{conf:.0%}"
strata_levels = causes if not levels else [f"{lv} · {c}" for lv in levels for c in causes]
tables = [{"key": "incidence", "title": "Cumulative incidence at chosen times", "columns": [
{"key": "group", "label": g if levels else "Curve", "type": "string"}, {"key": "cause", "label": "Cause", "type": "string"},
{"key": "time", "label": "Time", "type": "number"}, {"key": "cif", "label": "Cumulative incidence", "type": "number"},
{"key": "lower", "label": f"{pct} CI low", "type": "number"}, {"key": "upper", "label": f"{pct} CI high", "type": "number"},
], "rows": rows, "note": "Aalen–Johansen estimate; delta-method SE with a log–log interval."}]
if test_rows:
tables.append({"key": "tests", "title": "Group comparisons by cause", "columns": [
{"key": "cause", "label": "Cause", "type": "string"}, {"key": "gray", "label": "Gray's χ²", "type": "number"},
{"key": "gray_df", "label": "df", "type": "integer"}, {"key": "gray_p", "label": "Gray's p", "type": "pvalue"},
{"key": "chisq", "label": "Log-rank χ²", "type": "number"}, {"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "Log-rank p", "type": "pvalue"},
], "rows": test_rows, "note": "Gray's test compares the cumulative incidence curves; the cause-specific log-rank test compares the event rates among those still at risk."})
cs.publish({
"method": "survival.cif",
"methodVersion": "1.2.0",
"title": "Cumulative incidence (competing risks)" + (f" by {g}" if levels else ""),
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(len(t)),
"summary": f"{int(values['n_events'])} {cause} events, {int(values['n_competing'])} competing events, {int(values['n_censored'])} censored."
+ (f" {test_label.capitalize() if test_kind != 'gray' else test_label} for {cause}: {cs.fmt_p(values['p'])}." if levels else ""),
"apa": (f"χ²({values['df']:.0f}) = {cs.fmt_num(values['chisq'])}, {cs.fmt_p(values['p'])}" if levels
else f"{int(values['n_events'])} events of interest, N = {len(t)}"),
"statistics": [{"key": "n_events", "label": f"{cause} events", "value": values["n_events"], "format": "integer"},
{"key": "n_competing", "label": "Competing events", "value": values["n_competing"], "format": "integer"}]
+ ([{"key": "p", "label": f"{test_label} p", "value": values["p"], "format": "p"}] if levels else []),
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Censoring level: {censor}; causes: {', '.join(causes)}. 1 − Kaplan–Meier would overstate incidence when competing events occur."],
"charts": [cs.chart("cif", "cif-curve", "Cumulative incidence" + (f" by {g}" if levels else ""), {
"time": cs.col(tcol, curve["time"], "numeric"), "cif": cs.col("Cumulative incidence", curve["cif"], "numeric"),
"low": cs.col("lower", curve["low"], "numeric"), "high": cs.col("upper", curve["high"], "numeric"),
"strata": cs.col("Curve", curve["strata"], "categorical", levels=strata_levels),
})],
"values": values,
})
Shortened for the Academy: 1 chart(s) dropped to stay under 100 KB; 1 chart(s) dropped to stay under 100 KB.
The option Compare groups by offers Gray's test (the curves) and Cause-specific log-rank (the rates). The next step explains the choice.
Like the log-rank family, Gray's test can weight time. Gray weight power (ρ) multiplies each time's contribution by : 0 weighs all times equally, stresses early differences and late ones (cmprsk's rho). With , death by sex gives = 13.93. Choose before looking, from where you expect the curves to differ.
Check yourself
You expect a treatment to delay early relapses but not change the eventual share who relapse. Which Gray weight fits that expectation, chosen in advance?
Show the answer
Answer: a
With ρ > 0 the weight (1 − F̂(t−))^ρ is largest early, when few have had the event. Picking ρ after seeing several p-values inflates the false positive rate.
Two kinds of hazard
In the appThe two questions have different answers:
- Cause-specific hazard: among people still event-free, how fast does this event happen? Good for why, and fitted with a Cox model censoring the other causes.
- Subdistribution hazardFine–Gray modelModels how predictors change the cumulative incidence of one event, through its subdistribution hazard. (Fine–Gray): what changes the eventual share who have this event? Good for how many, and for risk prediction.
They can disagree. In mgus2, Fine–Gray gives an age ratio of 0.983 per year for PCM (95% interval 0.972 to 0.994), but a cause-specific Cox model shows almost no age effect. Older patients don't progress more slowly; they die first.
SHR = 0.98, 95% CI [0.97, 0.99], p = .002
- Robust Wald χ²
- 10.561
- df
- 2
- p
- .005
Effect size
- Subdistribution hazard ratio (age) 0.9828 95% CI [0.9719, 0.9939]
Plots
View data
| SHR | upper | Term | lower |
|---|---|---|---|
| 0.9828 | 0.9939 | age | 0.9719 |
| 0.7712 | 1.110 | sex: M | 0.5360 |
View data
| Cumulative incidence | Curve | etime |
|---|---|---|
| 0 | All | 0 |
| 0 | All | 2 |
| 0.0014 | All | 2 |
| 0.0014 | All | 4 |
| 0.0022 | All | 4 |
| 0.0022 | All | 5 |
| 0.0029 | All | 5 |
| 0.0029 | All | 6 |
| 0.0036 | All | 6 |
| 0.0036 | All | 8 |
| 0.0051 | All | 8 |
| 0.0051 | All | 9 |
| 0.0065 | All | 9 |
| 0.0065 | All | 10 |
| 0.0080 | All | 10 |
| 0.0080 | All | 11 |
| 0.0087 | All | 11 |
| 0.0087 | All | 12 |
| 0.0094 | All | 12 |
| 0.0094 | All | 13 |
| 0.0101 | All | 13 |
| 0.0101 | All | 14 |
| 0.0116 | All | 14 |
| 0.0116 | All | 16 |
| 0.0123 | All | 16 |
| 0.0123 | All | 17 |
| 0.0137 | All | 17 |
| 0.0137 | All | 21 |
| 0.0152 | All | 21 |
| 0.0152 | All | 22 |
| 0.0159 | All | 22 |
| 0.0159 | All | 23 |
| 0.0174 | All | 23 |
| 0.0174 | All | 29 |
| 0.0188 | All | 29 |
| 0.0188 | All | 30 |
| 0.0195 | All | 30 |
| 0.0195 | All | 33 |
| 0.0203 | All | 33 |
| 0.0203 | All | 34 |
| 0.0210 | All | 34 |
| 0.0210 | All | 35 |
| 0.0217 | All | 35 |
| 0.0217 | All | 36 |
| 0.0224 | All | 36 |
| 0.0224 | All | 38 |
| 0.0232 | All | 38 |
| 0.0232 | All | 39 |
| 0.0246 | All | 39 |
| 0.0246 | All | 42 |
| 0.0261 | All | 42 |
| 0.0261 | All | 44 |
| 0.0268 | All | 44 |
| 0.0268 | All | 45 |
| 0.0275 | All | 45 |
| 0.0275 | All | 51 |
| 0.0290 | All | 51 |
| 0.0290 | All | 52 |
| 0.0304 | All | 52 |
| 0.0304 | All | 56 |
First 60 of 178 rows.
Assumptions
- Events per variable — 57.5 events of pcm per coefficient.
- Proportional subdistribution hazards — Not tested; curves that cross or converge suggest a time-varying effect.
- Independent censoring — 409 of 1384 subjects are censored; 860 had a competing event.
Subdistribution hazard ratios
| Term | β | Robust SE | SHR | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| age | −0.0173 | 0.0057 | 0.9828 | 0.9719 | 0.9939 | −3.034 | .002 |
| sex: M | −0.2598 | 0.1856 | 0.7712 | 0.5360 | 1.110 | −1.399 | .162 |
Tests
| Test | χ² | df | p |
|---|---|---|---|
| Wald (robust) | 10.561 | 2 | .005 |
| Likelihood ratio (weighted, model-based) | 7.280 | 2 | .026 |
- Cause of interest: pcm; censoring: censored; competing: death. The weighted data have 41775 rows (survival::finegray). Ties: efron.
The exact R script · R R version 4.5.1 (2025-06-13)
# Fine–Gray competing-risks regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.finegray 1.0.1 · spec 9ec3b1c816ee142e
# Dataset: mgus2_cr (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(survival)
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mgus2_cr.parquet", col_select = c("etime", "event", "age", "sex")))
n_input <- nrow(df)
df[["event"]] <- factor(df[["event"]], levels = c("censored", "pcm", "death")) # stored level order
df[["sex"]] <- factor(df[["sex"]], levels = c("F", "M")) # stored level order
df <- df[stats::complete.cases(df[c("etime", "event", "age", "sex")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("etime", "event", "age", "sex")) # infinite values stop the run (registry/errors.yaml)
# %% Event types
tcol <- "etime"
ecol <- "event"
tt <- as.numeric(df[[tcol]])
if (any(tt < 0)) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = "zero or positive (survival times)", count = sum(tt < 0))
elevels <- levels(df[[ecol]])
censor_level <- "censored"
causes <- setdiff(elevels, censor_level)
if (length(causes) == 0) cs_error("CS_E_NO_EVENTS", event = sprintf("%s other than %s", ecol, censor_level))
cause_level <- causes[1]
if (cause_level == censor_level) stop("Choose a cause of interest that is not the censoring level")
if (!(cause_level %in% elevels)) cs_error("CS_E_NOT_A_LEVEL", level = cause_level, column = ecol)
if (length(causes) < 2) cs_error("CS_E_UNDEFINED", what = "The Fine–Gray model", reason = sprintf("%s needs at least two causes besides %s; with one cause use a Cox model", ecol, censor_level))
ev_str <- as.character(df[[ecol]])
# %% Predictors
preds <- c("age", "sex")
dd <- data.frame(.t = tt, .ev = factor(ev_str, levels = c(censor_level, causes)), .id = seq_along(tt))
# %% Predictors `preds` (treatment contrasts against the first stored level) into `dd`
labels <- character(0)
for (pname in preds) {
x <- df[[pname]]
if (is.factor(x)) {
if (nlevels(x) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = pname, min = 2, k = nlevels(x)) # a factor needs two levels with data
labels <- c(labels, paste0(pname, ": ", levels(x)[-1]))
} else {
labels <- c(labels, pname)
}
dd[[pname]] <- x
}
rhs <- if (length(preds)) paste(sprintf("`%s`", gsub("`", "\\\\`", preds)), collapse = " + ") else "1"
# %% Fine–Gray model: finegray weights + weighted Cox, robust variance clustered by subject
conf <- 0.95
ties <- "efron"
fg <- finegray(Surv(.t, .ev) ~ ., data = dd, etype = cause_level, id = .id)
ctl <- coxph.control(eps = 1e-12, toler.chol = 1e-15, iter.max = 60)
fit <- coxph(stats::as.formula(paste("Surv(fgstart, fgstop, fgstatus) ~", rhs)), data = fg, weights = fgwt,
cluster = .id, ties = ties, control = ctl)
beta <- unname(coef(fit))
if (anyNA(beta)) stop("Some coefficients could not be estimated (collinear predictors).")
V <- unname(fit$var)
naive_se <- sqrt(diag(unname(fit$naive.var)))
se <- sqrt(diag(V))
z <- beta / se
pv <- 2 * stats::pnorm(-abs(z))
q <- stats::qnorm(1 - (1 - conf) / 2)
shr <- exp(beta)
shr_lo <- exp(beta - q * se)
shr_hi <- exp(beta + q * se)
k <- length(beta)
lr <- 2 * diff(fit$loglik)
lr_p <- stats::pchisq(lr, k, lower.tail = FALSE)
wald <- drop(beta %*% solve(V, beta))
n_ev <- sum(ev_str == cause_level)
n_cens <- sum(ev_str == censor_level)
n_comp <- length(tt) - n_ev - n_cens
# %% Gray's test and cumulative incidence curves (cmprsk::cuminc)
g <- NULL
glevels <- "All"
ci <- cmprsk::cuminc(tt, ev_str, cencode = censor_level)
gray_chisq <- NULL
gray_df <- NULL
gray_p <- NULL
curve <- list(time = numeric(0), cif = numeric(0), strata = character(0))
for (lv in glevels) {
key <- paste(if (is.null(g)) "1" else lv, cause_level)
e <- ci[[key]]
curve$time <- c(curve$time, e$time)
curve$cif <- c(curve$cif, e$est)
curve$strata <- c(curve$strata, rep(lv, length(e$time)))
}
values <- list(
n = length(tt), n_events = n_ev, n_competing = n_comp, n_censored = n_cens, cause_label = cause_level, censor_label = censor_level,
n_rows_expanded = nrow(fg), n_coef = k, loglik = fit$loglik[2], loglik0 = fit$loglik[1], lr_chisq = lr, lr_df = k, lr_p = lr_p,
wald_chisq = wald, wald_p = stats::pchisq(wald, k, lower.tail = FALSE),
coef_1_label = labels[1], shr_1 = shr[1], shr_1_low = shr_lo[1], shr_1_high = shr_hi[1], p_1 = pv[1],
epv = n_ev / k, gray_chisq = gray_chisq, gray_df = gray_df, gray_p = gray_p
)
coef_rows <- list()
for (i in seq_along(labels)) {
lab <- labels[i]
vals <- list(coef = beta[i], se = se[i], naive_se = naive_se[i], shr = shr[i], shr_low = shr_lo[i], shr_high = shr_hi[i], z = z[i], p = pv[i])
for (key in names(vals)) values[[sprintf("%s[%s]", key, lab)]] <- vals[[key]]
coef_rows[[i]] <- c(list(term = lab), vals[c("coef", "se", "shr", "shr_low", "shr_high", "z", "p")])
}
# %% Assumptions
epv <- n_ev / k
assumptions <- list(
list(key = "events_per_variable", label = "Events per variable", status = if (epv < 10) "warn" else "pass",
detail = paste0(sprintf("%.1f events of %s per coefficient", epv, cause_level), if (epv < 10) " — fewer than 10; estimates may be unstable." else ".")),
list(key = "proportional_subdistribution_hazards", label = "Proportional subdistribution hazards", status = "info",
detail = "Not tested; curves that cross or converge suggest a time-varying effect."),
list(key = "censoring", label = "Independent censoring", status = "info",
detail = sprintf("%d of %d subjects are censored; %d had a competing event.", n_cens, length(tt), n_comp))
)
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
tests_rows <- list(
list(test = "Wald (robust)", chisq = wald, df = k, p = values$wald_p),
list(test = "Likelihood ratio (weighted, model-based)", chisq = lr, df = k, p = lr_p)
)
if (!is.null(gray_p)) tests_rows[[3]] <- list(test = sprintf("Gray's test (%s)", g), chisq = gray_chisq, df = gray_df, p = gray_p)
cs_publish(list(
method = "survival.finegray",
methodVersion = "1.0.1",
title = sprintf("Fine–Gray model for %s", cause_level),
engine = cs_engine_info("survival", "cmprsk", "codesplashr"),
n = length(tt),
summary = sprintf("Fine–Gray model for %s (%d events, %d competing): robust Wald χ²(%d) = %.2f, %s.", cause_level, n_ev, n_comp, k, wald, cs_fmt_p(values$wald_p)),
apa = sprintf("SHR = %s, %s CI [%s, %s], %s", cs_fmt_num(shr[1]), pct, cs_fmt_num(shr_lo[1]), cs_fmt_num(shr_hi[1]), cs_fmt_p(pv[1])),
statistics = list(
list(key = "wald_chisq", label = "Robust Wald χ²", value = wald), list(key = "lr_df", label = "df", value = k, format = "integer"),
list(key = "wald_p", label = "p", value = values$wald_p, format = "p")
),
tables = list(
list(key = "coefficients", title = "Subdistribution hazard ratios", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "coef", label = "β", type = "number"),
list(key = "se", label = "Robust SE", type = "number"), list(key = "shr", label = "SHR", type = "number"),
list(key = "shr_low", label = paste(pct, "CI low"), type = "number"), list(key = "shr_high", label = paste(pct, "CI high"), type = "number"),
list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue")
), rows = coef_rows),
list(key = "tests", title = "Tests", columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "chisq", label = "χ²", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")
), rows = tests_rows)
),
effectSizes = list(list(key = "shr_1", label = sprintf("Subdistribution hazard ratio (%s)", labels[1]), value = shr[1], ciLow = shr_lo[1],
ciHigh = shr_hi[1], ciLevel = conf, method = "Wald interval on log(SHR), robust SE")),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Cause of interest: %s; censoring: %s; competing: %s. The weighted data have %d rows (survival::finegray). Ties: %s.",
cause_level, censor_level, paste(setdiff(causes, cause_level), collapse = ", "), nrow(fg), ties)),
charts = list(
cs_chart("shr", "forest", "Subdistribution hazard ratios", list(
label = cs_col("Term", labels, "categorical", levels = labels), estimate = cs_col("SHR", shr, "numeric"),
low = cs_col("lower", shr_lo, "numeric"), high = cs_col("upper", shr_hi, "numeric")
), controls = list(reference = 1, log = TRUE)),
cs_chart("cif", "cif-curve", paste0("Cumulative incidence of ", cause_level, if (!is.null(g)) paste(" by", g) else ""), list(
time = cs_col(tcol, curve$time, "numeric"), cif = cs_col("Cumulative incidence", curve$cif, "numeric"),
strata = cs_col(if (is.null(g)) "Curve" else g, curve$strata, "categorical", levels = glevels)
))
),
values = values
))
SHR = 0.98, 95% CI [0.97, 0.99], p = .002
- Robust Wald χ²
- 10.561
- df
- 2
- p
- .005
Effect size
- Subdistribution hazard ratio (age) 0.9828 95% CI [0.9719, 0.9939]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Events per variable — 57.5 events of pcm per coefficient.
- Proportional subdistribution hazards — Not tested; curves that cross or converge suggest a time-varying effect.
- Independent censoring — 409 of 1384 subjects are censored; 860 had a competing event.
Subdistribution hazard ratios
| Term | β | Robust SE | SHR | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| age | −0.0173 | 0.0057 | 0.9828 | 0.9719 | 0.9939 | −3.034 | .002 |
| sex: M | −0.2598 | 0.1856 | 0.7712 | 0.5360 | 1.110 | −1.399 | .162 |
Tests
| Test | χ² | df | p |
|---|---|---|---|
| Wald (robust) | 10.561 | 2 | .005 |
| Likelihood ratio (weighted, model-based) | 7.280 | 2 | .026 |
- Cause of interest: pcm; censoring: censored; competing: death. The weighted data have 41775 rows (survival::finegray). Ties: efron.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Fine–Gray competing-risks regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.finegray 1.0.1 · spec 9ec3b1c816ee142e
# Dataset: mgus2_cr (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import survival as sv # Aalen–Johansen cumulative incidence (curves)
from codesplash.stats import survival_adv as sa # finegray data, weighted Cox with robust SEs, Gray's test
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mgus2_cr.parquet", columns=["etime", "event", "age", "sex"])
n_input = len(df)
df["event"] = pd.Categorical(df["event"], categories=["censored", "pcm", "death"]) # stored level order
df["sex"] = pd.Categorical(df["sex"], categories=["F", "M"]) # stored level order
df = df.dropna(subset=["etime", "event", "age", "sex"]) # listwise deletion over the analysis columns
df["event"] = df["event"].cat.remove_unused_categories()
df["sex"] = df["sex"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["etime", "event", "age", "sex"]) # infinite values stop the run (registry/errors.yaml)
# %% Event types
tcol = "etime"
ecol = "event"
t = df[tcol].to_numpy(dtype=float)
if (t < 0).any():
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement="zero or positive (survival times)", count=int((t < 0).sum()))
elevels = [str(x) for x in df[ecol].cat.categories]
censor_level = "censored"
causes = [lv for lv in elevels if lv != censor_level]
if not causes:
cs.cs_error("CS_E_NO_EVENTS", event=f"{ecol} other than {censor_level}")
cause_level = causes[0]
if cause_level == censor_level:
raise ValueError("Choose a cause of interest that is not the censoring level")
if cause_level not in elevels:
cs.cs_error("CS_E_NOT_A_LEVEL", level=cause_level, column=ecol)
if len(causes) < 2:
cs.cs_error("CS_E_UNDEFINED", what="The Fine–Gray model", reason=f"{ecol} needs at least two causes besides {censor_level}; with one cause use a Cox model")
ev_str = df[ecol].astype(str).to_numpy()
code = np.where(ev_str == censor_level, 0, np.where(ev_str == cause_level, 1, 2)) # 0 censored, 1 cause, 2 competing
# %% Predictors
preds = ["age", "sex"]
# %% Design matrix for `preds` (treatment contrasts against the first stored level)
cols, labels, terms = [], [], []
for pname in preds:
s = df[pname]
if isinstance(s.dtype, pd.CategoricalDtype):
lv = [str(x) for x in s.cat.categories]
if len(lv) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=pname, min=2, k=len(lv)) # a factor needs two levels with data
idx = []
for level in lv[1:]:
idx.append(len(cols))
cols.append((s.astype(str) == level).to_numpy(dtype=float))
labels.append(f"{pname}: {level}")
terms.append(idx)
else:
terms.append([len(cols)])
cols.append(s.to_numpy(dtype=float))
labels.append(pname)
X = np.column_stack(cols) if cols else np.zeros((len(df), 0))
# %% Fine–Gray model: finegray weights + weighted Cox, robust variance clustered by subject
conf = 0.95
ties = "efron"
fg = sa.finegray_expand(t, code, 1)
fit = sa.cox_cp(fg["start"], fg["stop"], fg["status"] == 1, X[fg["row"]], weights=fg["wt"], ties=ties, cluster=fg["row"])
beta = fit["coef"]
naive_se = np.sqrt(np.diag(fit["cov"]))
V = fit["rcov"]
se = np.sqrt(np.diag(V))
z = beta / se
pv = 2 * stats.norm.sf(np.abs(z))
q = stats.norm.ppf(1 - (1 - conf) / 2)
shr, shr_lo, shr_hi = np.exp(beta), np.exp(beta - q * se), np.exp(beta + q * se)
k = len(beta)
lr_p = float(stats.chi2.sf(fit["lr"], k))
wald = float(beta @ np.linalg.solve(V, beta))
n_ev, n_comp, n_cens = int(np.sum(code == 1)), int(np.sum(code == 2)), int(np.sum(code == 0))
# %% Gray's test and cumulative incidence curves
g = None
glevels = ["All"]
gcodes = np.zeros(len(t), dtype=int)
gray_chisq = gray_df = gray_p = None
curve = {"time": [], "cif": [], "strata": []}
for i, lv in enumerate(glevels):
m = gcodes == i
res = sv.cif(t[m], code[m], 2, conf=conf)
curve["time"] += [0.0] + res["time"].tolist()
curve["cif"] += [0.0] + res["cif"][0].tolist()
curve["strata"] += [lv] * (len(res["time"]) + 1)
values = {
"n": float(len(t)), "n_events": float(n_ev), "n_competing": float(n_comp), "n_censored": float(n_cens),
"cause_label": cause_level, "censor_label": censor_level, "n_rows_expanded": float(len(fg["row"])), "n_coef": float(k),
"loglik": fit["loglik"], "loglik0": fit["loglik0"], "lr_chisq": fit["lr"], "lr_df": float(k), "lr_p": lr_p,
"wald_chisq": wald, "wald_p": float(stats.chi2.sf(wald, k)),
"coef_1_label": labels[0], "shr_1": float(shr[0]), "shr_1_low": float(shr_lo[0]), "shr_1_high": float(shr_hi[0]), "p_1": float(pv[0]),
"epv": n_ev / k, "gray_chisq": gray_chisq, "gray_df": gray_df, "gray_p": gray_p,
}
coef_rows = []
for i, lab in enumerate(labels):
for key, val in (("coef", beta[i]), ("se", se[i]), ("naive_se", naive_se[i]), ("shr", shr[i]), ("shr_low", shr_lo[i]),
("shr_high", shr_hi[i]), ("z", z[i]), ("p", pv[i])):
values[f"{key}[{lab}]"] = float(val)
coef_rows.append({"term": lab, "coef": float(beta[i]), "se": float(se[i]), "shr": float(shr[i]), "shr_low": float(shr_lo[i]),
"shr_high": float(shr_hi[i]), "z": float(z[i]), "p": float(pv[i])})
# %% Assumptions
epv = n_ev / k
assumptions = [
{"key": "events_per_variable", "label": "Events per variable", "status": "warn" if epv < 10 else "pass",
"detail": f"{epv:.1f} events of {cause_level} per coefficient" + (" — fewer than 10; estimates may be unstable." if epv < 10 else ".")},
{"key": "proportional_subdistribution_hazards", "label": "Proportional subdistribution hazards", "status": "info",
"detail": "Not tested; curves that cross or converge suggest a time-varying effect."},
{"key": "censoring", "label": "Independent censoring", "status": "info",
"detail": f"{n_cens} of {len(t)} subjects are censored; {n_comp} had a competing event."},
]
# %% Result
pct = f"{conf:.0%}"
tests_rows = [
{"test": "Wald (robust)", "chisq": wald, "df": float(k), "p": values["wald_p"]},
{"test": "Likelihood ratio (weighted, model-based)", "chisq": fit["lr"], "df": float(k), "p": lr_p},
]
if gray_p is not None:
tests_rows.append({"test": f"Gray's test ({g})", "chisq": gray_chisq, "df": gray_df, "p": gray_p})
cs.publish({
"method": "survival.finegray",
"methodVersion": "1.0.1",
"title": f"Fine–Gray model for {cause_level}",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(len(t)),
"summary": f"Fine–Gray model for {cause_level} ({n_ev} events, {n_comp} competing): robust Wald χ²({k}) = {wald:.2f}, {cs.fmt_p(values['wald_p'])}.",
"apa": f"SHR = {cs.fmt_num(shr[0])}, {pct} CI [{cs.fmt_num(shr_lo[0])}, {cs.fmt_num(shr_hi[0])}], {cs.fmt_p(pv[0])}",
"statistics": [
{"key": "wald_chisq", "label": "Robust Wald χ²", "value": wald}, {"key": "lr_df", "label": "df", "value": float(k), "format": "integer"},
{"key": "wald_p", "label": "p", "value": values["wald_p"], "format": "p"},
],
"tables": [
{"key": "coefficients", "title": "Subdistribution hazard ratios", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "coef", "label": "β", "type": "number"},
{"key": "se", "label": "Robust SE", "type": "number"}, {"key": "shr", "label": "SHR", "type": "number"},
{"key": "shr_low", "label": f"{pct} CI low", "type": "number"}, {"key": "shr_high", "label": f"{pct} CI high", "type": "number"},
{"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
], "rows": coef_rows},
{"key": "tests", "title": "Tests", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "chisq", "label": "χ²", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"},
], "rows": tests_rows},
],
"effectSizes": [{"key": "shr_1", "label": f"Subdistribution hazard ratio ({labels[0]})", "value": float(shr[0]), "ciLow": float(shr_lo[0]),
"ciHigh": float(shr_hi[0]), "ciLevel": conf, "method": "Wald interval on log(SHR), robust SE"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Cause of interest: {cause_level}; censoring: {censor_level}; competing: {', '.join(c for c in causes if c != cause_level)}. "
f"The weighted data have {len(fg['row'])} rows (survival::finegray). Ties: {ties}."],
"charts": [
cs.chart("shr", "forest", "Subdistribution hazard ratios", {
"label": cs.col("Term", labels, "categorical", levels=labels), "estimate": cs.col("SHR", shr, "numeric"),
"low": cs.col("lower", shr_lo, "numeric"), "high": cs.col("upper", shr_hi, "numeric"),
}, controls={"reference": 1, "log": True}),
cs.chart("cif", "cif-curve", f"Cumulative incidence of {cause_level}" + (f" by {g}" if g else ""), {
"time": cs.col(tcol, curve["time"], "numeric"), "cif": cs.col("Cumulative incidence", curve["cif"], "numeric"),
"strata": cs.col(g or "Curve", curve["strata"], "categorical", levels=glevels),
}),
],
"values": values,
})
Check your understanding
CheckpointCheck yourself
What is wrong with treating competing deaths as ordinary censoring when you report the probability of relapse?
Show the answer
Answer: b
1 − Kaplan–Meier answers "what if death were removed?", a question that's rarely the one you're asking when you plan care.
Check yourself
A clinician asks: "Of 100 patients like this one, how many will have a stroke within 5 years, given that many will die first?" Which analysis answers that?
Show the answer
Answer: a
Cumulative incidence is the real-world probability. Cause-specific hazards address how fast strokes occur among those alive, which matters for understanding mechanism.
Check yourself
Gray's test tells you what?
Show the answer
Answer: b
Its null hypothesis is that groups have the same cumulative incidence function for the specified cause.
Recap
Recap- A competing event prevents the event of interest, so it isn't censoring.
- Report cumulative incidence, not 1 − Kaplan–Meier.
- Gray's test compares cumulative incidence between groups.
- Cause-specific hazards explain mechanism; Fine–Gray describes how many have the event.
Concepts in this lesson