Skip to content

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.

Advanced ~14 min8 steps

What runs in CodeSplash

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

Read first

01

When another event gets there first

Read

The 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.

02

Predict the error

Predict

Predict 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?

Understates the risk of PCMGets it about rightOverstates the risk of 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.

03

Cumulative incidence

In the app

The 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 tt. Aalen–Johansen accumulates hazards among those who have had no event of any kind:

F^k(t)=∑tj≤tS^(tj−1) dkjnj\hat F_k(t) = \sum_{t_j \le t} \hat S(t_{j-1})\,\frac{d_{kj}}{n_j}

The incidences of all causes and the share still event-free add to one at every time.

Cumulative incidence (competing risks)How likely is each type of event by a given time when other events compete?
View data
monthscumulative incidencecause
00relapse
0.10000.0067relapse
0.20000.0200relapse
0.40000.0267relapse
0.50000.0267relapse
0.80000.0333relapse
0.90000.0400relapse
1.1000.0467relapse
1.2000.0533relapse
1.3000.0667relapse
1.4000.0733relapse
1.5000.0800relapse
1.8000.0867relapse
2.2000.0867relapse
2.3000.0867relapse
2.4000.0867relapse
2.5000.0867relapse
2.8000.0933relapse
2.9000.1000relapse
3.1000.1000relapse
3.4000.1000relapse
3.6000.1133relapse
3.9000.1267relapse
40.1333relapse
4.1000.1467relapse
4.2000.1533relapse
4.4000.1533relapse
4.5000.1600relapse
4.6000.1667relapse
4.7000.1733relapse
4.9000.1800relapse
5.2000.1800relapse
5.4000.1867relapse
5.8000.1933relapse
60.2000relapse
6.2000.2000relapse
6.3000.2067relapse
6.4000.2067relapse
6.5000.2067relapse
6.8000.2067relapse
7.3000.2067relapse
7.4000.2133relapse
7.5000.2267relapse
80.2333relapse
8.4000.2400relapse
8.5000.2400relapse
9.4000.2400relapse
9.7000.2400relapse
9.8000.2467relapse
10.2000.2533relapse
10.5000.2601relapse
10.6000.2668relapse
10.7000.2736relapse
11.1000.2804relapse
11.5000.2941relapse
12.1000.3010relapse
12.6000.3079relapse
130.3149relapse
13.3000.3219relapse
13.4000.3289relapse

First 60 of 172 rows.

Cumulative incidence (competing risks)Recorded · Python and R agreeRecorded 2026-11-21 · 39 values compared
R

115 events of interest, N = 1384

pcm events
115
Competing events
860

Plots

Cumulative incidenceHow likely is each type of event by a given time when other events compete?
View data
Cumulative incidenceupperlowerCurveetime
0——pcm0
0——pcm1
0.00140.00500.0003pcm2
0.00140.00500.0003pcm3
0.00220.00610.0006pcm4
0.00290.00710.0010pcm5
0.00360.00810.0014pcm6
0.00360.00810.0014pcm7
0.00510.01010.0023pcm8
0.00650.01200.0032pcm9
0.00800.01380.0043pcm10
0.00870.01480.0048pcm11
0.00940.01570.0053pcm12
0.01010.01660.0058pcm13
0.01160.01840.0069pcm14
0.01160.01840.0069pcm15
0.01230.01920.0075pcm16
0.01370.02100.0086pcm17
0.01370.02100.0086pcm18
0.01370.02100.0086pcm19
0.01370.02100.0086pcm20
0.01520.02270.0097pcm21
0.01590.02360.0103pcm22
0.01740.02530.0114pcm23
0.01740.02530.0114pcm24
0.01740.02530.0114pcm25
0.01740.02530.0114pcm26
0.01740.02530.0114pcm27
0.01740.02530.0114pcm28
0.01880.02700.0126pcm29
0.01950.02790.0132pcm30
0.01950.02790.0132pcm31
0.01950.02790.0132pcm32
0.02030.02870.0138pcm33
0.02100.02960.0144pcm34
0.02170.03040.0150pcm35
0.02240.03130.0156pcm36
0.02240.03130.0156pcm37
0.02320.03210.0162pcm38
0.02460.03380.0174pcm39
0.02460.03380.0174pcm40
0.02460.03380.0174pcm41
0.02610.03550.0186pcm42
0.02610.03550.0186pcm43
0.02680.03630.0192pcm44
0.02750.03710.0198pcm45
0.02750.03710.0198pcm46
0.02750.03710.0198pcm47
0.02750.03710.0198pcm48
0.02750.03710.0198pcm49
0.02750.03710.0198pcm50
0.02900.03880.0211pcm51
0.03040.04050.0223pcm52
0.03040.04050.0223pcm53
0.03040.04050.0223pcm54
0.03040.04050.0223pcm55
0.03110.04130.0229pcm56
0.03260.04300.0242pcm57
0.03260.04300.0242pcm58
0.03260.04300.0242pcm59

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

CurveCauseTimeCumulative incidence95% CI low95% CI high
Allpcm600.03410.02540.0447
Allpcm1200.06370.05130.0779
Allpcm2400.09980.08170.1200
Allpcm600———
Alldeath600.32040.29590.3451
Alldeath1200.53180.50390.5589
Alldeath2400.72400.69210.7533
Alldeath600———

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
))
Python

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

CurveCauseTimeCumulative incidence95% CI low95% CI high
Allpcm600.03410.02540.0447
Allpcm1200.06370.05130.0779
Allpcm2400.09980.08170.1200
Allpcm600———
Alldeath600.32040.29590.3451
Alldeath1200.53180.50390.5589
Alldeath2400.72400.69210.7533
Alldeath600———

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,
})
04

Compare the two for yourself

Read
Python
import 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))
R
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)$surv
05

Gray's test

In the app

To 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: χ2\chi^2 = 11.65, p < .001.

Cumulative incidence (competing risks) by sexRecorded · Python and R agreeRecorded 2026-11-21 · 77 values compared
R

χ²(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

sexCauseTimeCumulative incidence90% CI low90% CI high
Allpcm1100.06000.04980.0714
Allpcm2100.09380.07980.1091
Allpcm3200.11770.09580.1420
Alldeath1100.50450.48140.5272
Alldeath2100.69270.66790.7161
Alldeath3200.77190.73910.8012
Fpcm1100.06570.05050.0836
Fpcm2100.09920.07890.1222
Fpcm3200.12990.09660.1684
Fdeath1100.45370.41970.4871
Fdeath2100.66230.62430.6974
Fdeath3200.73830.68800.7818
Mpcm1100.05530.04230.0707
Mpcm2100.08910.07060.1102
Mpcm3200.10450.08030.1322
Mdeath1100.54740.51580.5779
Mdeath2100.71890.68540.7494
Mdeath3200.79940.75690.8353

Aalen–Johansen estimate; delta-method SE with a log–log interval.

Group comparisons by cause

CauseGray's χ²dfGray's pLog-rank χ²dfLog-rank p
pcm1.1951.2740.10061.751
death11.6511< .00110.9861< .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
))
Python

χ²(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

sexCauseTimeCumulative incidence90% CI low90% CI high
Allpcm1100.06000.04980.0714
Allpcm2100.09380.07980.1091
Allpcm3200.11770.09580.1420
Alldeath1100.50450.48140.5272
Alldeath2100.69270.66790.7161
Alldeath3200.77190.73910.8012
Fpcm1100.06570.05050.0836
Fpcm2100.09920.07890.1222
Fpcm3200.12990.09660.1684
Fdeath1100.45370.41970.4871
Fdeath2100.66230.62430.6974
Fdeath3200.73830.68800.7818
Mpcm1100.05530.04230.0707
Mpcm2100.08910.07060.1102
Mpcm3200.10450.08030.1322
Mdeath1100.54740.51580.5779
Mdeath2100.71890.68540.7494
Mdeath3200.79940.75690.8353

Aalen–Johansen estimate; delta-method SE with a log–log interval.

Group comparisons by cause

CauseGray's χ²dfGray's pLog-rank χ²dfLog-rank p
pcm1.1951.2740.10061.751
death11.6511< .00110.9861< .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 (1−F^(t−))ρ(1-\hat F(t^-))^\rho: 0 weighs all times equally, ρ>0\rho > 0 stresses early differences and ρ<0\rho < 0 late ones (cmprsk's rho). With ρ=1\rho = 1, death by sex gives χ2\chi^2 = 13.93. Choose ρ\rho 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.

06

Two kinds of hazard

In the app

The 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.

Fine–Gray model for pcmRecorded · Python and R agreeRecorded 2026-11-17 · 40 values compared
R

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

Subdistribution hazard ratiosHow large are several estimates, how precise, and which exclude the null?
View data
SHRupperTermlower
0.98280.9939age0.9719
0.77121.110sex: M0.5360
Cumulative incidence of pcmHow likely is each type of event by a given time when other events compete?
View data
Cumulative incidenceCurveetime
0All0
0All2
0.0014All2
0.0014All4
0.0022All4
0.0022All5
0.0029All5
0.0029All6
0.0036All6
0.0036All8
0.0051All8
0.0051All9
0.0065All9
0.0065All10
0.0080All10
0.0080All11
0.0087All11
0.0087All12
0.0094All12
0.0094All13
0.0101All13
0.0101All14
0.0116All14
0.0116All16
0.0123All16
0.0123All17
0.0137All17
0.0137All21
0.0152All21
0.0152All22
0.0159All22
0.0159All23
0.0174All23
0.0174All29
0.0188All29
0.0188All30
0.0195All30
0.0195All33
0.0203All33
0.0203All34
0.0210All34
0.0210All35
0.0217All35
0.0217All36
0.0224All36
0.0224All38
0.0232All38
0.0232All39
0.0246All39
0.0246All42
0.0261All42
0.0261All44
0.0268All44
0.0268All45
0.0275All45
0.0275All51
0.0290All51
0.0290All52
0.0304All52
0.0304All56

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 SESHR95% CI low95% CI highzp
age−0.01730.00570.98280.97190.9939−3.034.002
sex: M−0.25980.18560.77120.53601.110−1.399.162

Tests

Testχ²dfp
Wald (robust)10.5612.005
Likelihood ratio (weighted, model-based)7.2802.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
))
Python

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 SESHR95% CI low95% CI highzp
age−0.01730.00570.98280.97190.9939−3.034.002
sex: M−0.25980.18560.77120.53601.110−1.399.162

Tests

Testχ²dfp
Wald (robust)10.5612.005
Likelihood ratio (weighted, model-based)7.2802.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,
})
07

Check your understanding

Checkpoint

Check 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.

08

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