Skip to content

FTime to event · survival.cif

Cumulative incidence with competing risks

What is the probability of each type of event over time when other events compete?

Estimates the cumulative incidence of each cause with the Aalen–Johansen estimator — the correct summary when another event (such as death) prevents the event of interest; 1 − Kaplan–Meier overstates it. Reports incidence at chosen times with delta-method intervals and, with groups, Gray's test of the curves and cause-specific log-rank tests.

Verified in Python and R Python and R agree to 10 decimals Also called Gray's test, Gray competing risks test, Aalen–Johansen…

A real result

Example “Mgus overall”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Mgus overallmgus2_cr · event: event · time: etime
  • Mgus by sexmgus2_cr · event: event · group: sex · time: etime
  • Lung ecog as causeslung · event: ecog · time: time
  • Mgus by sex cause specificmgus2_cr · event: event · group: sex · time: etime
  • Mgus gray rho1mgus2_cr · event: event · group: sex · time: etime
  • Guide gray rho neglife_gray_guide · event: status · group: group · time: time
  • Guide graylife_gray_guide · event: status · group: group · time: time
  • Degenerate n3mgus2_cr · event: event · time: etime

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Time-to-event: median survival, KM curve · Statistics Guide · A — Describe data
  • Competing risks: Fine–Gray · Statistics Guide · F — Time-to-event analysis

What you need

Timenumeric · 1 column
Follow-up time until the first event or censoring.
Event typecategorical · 1 column · 2–20 levels
Which event happened first — one level means censored, every other level is a competing cause.
Groupscategorical / boolean · 0–1 column · 2–20 levels
Optional — curves per group and cause-specific log-rank tests.

Choices you make

hypothesis

Censoring leveldefault —

The level that means "no event yet" (default the first level).

Cause of interestdefault —

The cause tested between groups and named in the summary (default the first cause).

Compare groups bydefault gray

With groups: compare the cumulative incidence curves themselves, or the rates of the cause.

  • Gray's test (the curves)(default) — Compares cumulative incidence directly, so it answers how many events each group ends up with.
  • Cause-specific log-rank (the rates) — Compares the event rate among those still at risk, treating other causes as censoring.
Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

Advanced

Gray weight power (ρ)default 0

Weights each time by (1 − F̂(t−))^ρ: 0 weights all times equally; ρ > 0 stresses early differences, ρ < 0 late ones. Fix it in advance.

statistics

Report incidence at timesdefault

Times for the incidence table (default 25%, 50% and 75% of the longest follow-up).

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Non-informative censoring

    Censoring must be unrelated to the risk of every cause.

  • Number of events

    Each cause needs enough events for a stable curve.

What it reports

  • Tests: Equal cumulative incidence or cause-specific hazards for the cause of interest
n
How many independent units the analysis used; it sets precision and power.
n_censored
How many independent units the analysis used; it sets precision and power.
n_events
How many independent units the analysis used; it sets precision and power.
n_competing
How many independent units the analysis used; it sets precision and power.
cause_label
The event type the test and the summary focus on; every other event type competes with it.
censor_label
The level of the event column that means no event has happened yet.
n_causes
How many independent units the analysis used; it sets precision and power.
n_groups
How many independent units the analysis used; it sets precision and power.
chisq
A sum of squared, scaled differences between observed and expected counts or estimates.
df
How much independent information is left to estimate variability after fitting the model.
p
How surprising your data would be if the null hypothesis were true, as a probability.
test_kind
Which comparison produced the p-value on this card, among those the method offers.
test_label
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.

Per group, level or term: events[<cause>], cif[<group>·<cause>@<time>], cif_low[<group>·<cause>@<time>], cif_high[<group>·<cause>@<time>], chisq_cause[<cause>], p_cause[<cause>], gray_chisq[<cause>], gray_p[<cause>]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses survival, nanoparquet, codesplashr.

Default traps between the two languages

  • R takes the Aalen–Johansen estimate and its standard error from survfit's multi-state fit; Python computes the same estimate and the Marubini–Valsecchi delta-method variance (equal to survfit's for unweighted data) in codesplash.stats.survival.cif. Intervals use the log–log transformation in both.
  • Gray's test: R calls cmprsk::cuminc; Python computes it in survival_adv.gray_test, shared with Fine–Gray regression. The covariance's tie factors were identified numerically from cuminc's output on small tied data and aren't from a publication. Where the variance is singular cuminc reports −1 and Python NaN (66 of 3,800 very small tied data sets, none in the fixtures).
Python

The exact script CodeSplash ran for example “Mgus overall” · 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,
})
R

The exact script CodeSplash ran for example “Mgus overall” · 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
))

Sources

  • Gray, R. J. (1988). A class of K-sample tests for comparing the cumulative incidence of a competing risk. The Annals of Statistics, 16, 1141–1154.
  • Aalen, O. O., & Johansen, S. (1978). An empirical transition matrix for non-homogeneous Markov chains based on censored observations. Scandinavian Journal of Statistics, 5, 141–150.
  • Marubini, E., & Valsecchi, M. G. (1995). Analysing survival data from clinical trials and observational studies. Wiley.
  • Putter, H., Fiocco, M., & Geskus, R. B. (2007). Tutorial in biostatistics: competing risks and multi-state models. Statistics in Medicine, 26, 2389–2430.

From the CodeSplash method registry · survival.cif v1.2.0.