FTime to event · survival.finegray
Fine–Gray competing-risks regression
Which factors are associated with the cumulative incidence of an event when other events compete?
Fits the Fine–Gray subdistribution hazards model for one cause of interest: subjects who have a competing event stay in the risk set with weights from the censoring distribution, so the subdistribution hazard ratios describe effects on the cumulative incidence of that cause. Uses survival::finegray with a weighted Cox model and robust standard errors. With groups, Gray's test compares the cumulative incidence curves.
A real result
Example “Mgus pcm”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
SHR = 0.98, 95% CI [0.97, 0.99], p = .002
- Robust Wald χ²
- 10.561
- df
- 2
- p
- .005
Effect size
- Subdistribution hazard ratio (age) 0.9828 95% CI [0.9719, 0.9939]
Plots
View data
| SHR | upper | Term | lower |
|---|---|---|---|
| 0.9828 | 0.9939 | age | 0.9719 |
| 0.7712 | 1.110 | sex: M | 0.5360 |
View data
| Cumulative incidence | Curve | etime |
|---|---|---|
| 0 | All | 0 |
| 0 | All | 2 |
| 0.0014 | All | 2 |
| 0.0014 | All | 4 |
| 0.0022 | All | 4 |
| 0.0022 | All | 5 |
| 0.0029 | All | 5 |
| 0.0029 | All | 6 |
| 0.0036 | All | 6 |
| 0.0036 | All | 8 |
| 0.0051 | All | 8 |
| 0.0051 | All | 9 |
| 0.0065 | All | 9 |
| 0.0065 | All | 10 |
| 0.0080 | All | 10 |
| 0.0080 | All | 11 |
| 0.0087 | All | 11 |
| 0.0087 | All | 12 |
| 0.0094 | All | 12 |
| 0.0094 | All | 13 |
| 0.0101 | All | 13 |
| 0.0101 | All | 14 |
| 0.0116 | All | 14 |
| 0.0116 | All | 16 |
| 0.0123 | All | 16 |
| 0.0123 | All | 17 |
| 0.0137 | All | 17 |
| 0.0137 | All | 21 |
| 0.0152 | All | 21 |
| 0.0152 | All | 22 |
| 0.0159 | All | 22 |
| 0.0159 | All | 23 |
| 0.0174 | All | 23 |
| 0.0174 | All | 29 |
| 0.0188 | All | 29 |
| 0.0188 | All | 30 |
| 0.0195 | All | 30 |
| 0.0195 | All | 33 |
| 0.0203 | All | 33 |
| 0.0203 | All | 34 |
| 0.0210 | All | 34 |
| 0.0210 | All | 35 |
| 0.0217 | All | 35 |
| 0.0217 | All | 36 |
| 0.0224 | All | 36 |
| 0.0224 | All | 38 |
| 0.0232 | All | 38 |
| 0.0232 | All | 39 |
| 0.0246 | All | 39 |
| 0.0246 | All | 42 |
| 0.0261 | All | 42 |
| 0.0261 | All | 44 |
| 0.0268 | All | 44 |
| 0.0268 | All | 45 |
| 0.0275 | All | 45 |
| 0.0275 | All | 51 |
| 0.0290 | All | 51 |
| 0.0290 | All | 52 |
| 0.0304 | All | 52 |
| 0.0304 | All | 56 |
First 60 of 178 rows.
Assumptions
- Events per variable — 57.5 events of pcm per coefficient.
- Proportional subdistribution hazards — Not tested; curves that cross or converge suggest a time-varying effect.
- Independent censoring — 409 of 1384 subjects are censored; 860 had a competing event.
Subdistribution hazard ratios
| Term | β | Robust SE | SHR | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| age | −0.0173 | 0.0057 | 0.9828 | 0.9719 | 0.9939 | −3.034 | .002 |
| sex: M | −0.2598 | 0.1856 | 0.7712 | 0.5360 | 1.110 | −1.399 | .162 |
Tests
| Test | χ² | df | p |
|---|---|---|---|
| Wald (robust) | 10.561 | 2 | .005 |
| Likelihood ratio (weighted, model-based) | 7.280 | 2 | .026 |
- Cause of interest: pcm; censoring: censored; competing: death. The weighted data have 41775 rows (survival::finegray). Ties: efron.
SHR = 0.98, 95% CI [0.97, 0.99], p = .002
- Robust Wald χ²
- 10.561
- df
- 2
- p
- .005
Effect size
- Subdistribution hazard ratio (age) 0.9828 95% CI [0.9719, 0.9939]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Events per variable — 57.5 events of pcm per coefficient.
- Proportional subdistribution hazards — Not tested; curves that cross or converge suggest a time-varying effect.
- Independent censoring — 409 of 1384 subjects are censored; 860 had a competing event.
Subdistribution hazard ratios
| Term | β | Robust SE | SHR | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| age | −0.0173 | 0.0057 | 0.9828 | 0.9719 | 0.9939 | −3.034 | .002 |
| sex: M | −0.2598 | 0.1856 | 0.7712 | 0.5360 | 1.110 | −1.399 | .162 |
Tests
| Test | χ² | df | p |
|---|---|---|---|
| Wald (robust) | 10.561 | 2 | .005 |
| Likelihood ratio (weighted, model-based) | 7.280 | 2 | .026 |
- Cause of interest: pcm; censoring: censored; competing: death. The weighted data have 41775 rows (survival::finegray). Ties: efron.
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 pcmmgus2_cr · event: event · predictors: age, sex · time: etime
- Mgus death graymgus2_cr · event: event · group: sex · predictors: age · time: etime
- Crsim arms grays2_crsim · event: outcome · group: arm · predictors: arm, risk score · time: days
- Degenerate n3mgus2_cr · event: event · predictors: age, sex · time: etime
- Degenerate single levelmgus2_cr · event: event · predictors: age, sex · time: etime
In the guides
Where it sits in the decision guides
- Time-to-event: Cox, survival models · Statistics Guide · D — Predict an outcome
- Competing risks: Fine–Gray · Statistics Guide · F — Time-to-event analysis
- Interval censoring, recurrent events, delayed entry · 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 · 3–20 levels
- Which event happened first — one level means censored, the others are causes (at least two, so they compete).
- Predictorsnumeric / categorical / boolean · 1–20 columns · 2–30 levels
- Covariates. Categorical predictors use treatment contrasts against their first stored level.
- Groups for Gray's testcategorical / boolean · 0–1 column · 2–20 levels
- Optional — compare the cumulative incidence of the cause between groups (Gray's test) and draw a curve per group.
Choices you make
hypothesis
- Censoring leveldefault —
The level that means "no event yet" (default the first level).
- Cause of interestdefault —
The cause whose cumulative incidence is modeled (default the first cause after the censoring level).
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
options
- Tied event timesdefault efron
How tied event times enter the partial likelihood. Efron is more accurate; Breslow matches older software.
- Efron (coxph's default)(default) — Approximates the likelihood for tied times more closely; the usual choice.
- Breslow — Uses a plainer approximation; matches SAS and Stata defaults, and is less accurate with many ties.
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.
Proportional subdistribution hazards
The effect on the subdistribution hazard is constant over time; inspect the cumulative incidence curves.
Events per variable
At least about 10 events of the cause of interest per coefficient.
Independent censoring
Censoring must be unrelated to the risk of any cause (the weights come from the censoring distribution).
What it reports
- Tests: Model robust Wald test
- Tests: First predictor's subdistribution hazard ratio
- Tests: Gray's test: equal cumulative incidence across groups
- n
- 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.
- n_censored
- 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_rows_expanded
- How many independent units the analysis used; it sets precision and power.
- n_coef
- How many coefficients the model estimated, counting the intercept.
- loglik
- The logarithm of the likelihood; higher (less negative) means the model fits the data better.
- loglik0
- How well a model with no predictors fits. The likelihood-ratio test compares the fitted model with it.
- lr_chisq
- Compares nested models by how much the log-likelihood improves when parameters are added.
- lr_df
- Compares nested models by how much the log-likelihood improves when parameters are added.
- lr_p
- Compares nested models by how much the log-likelihood improves when parameters are added.
- wald_chisq
- A sum of squared, scaled differences between observed and expected counts or estimates.
- wald_p
- Tests a parameter by dividing its estimate by its standard error; quick, but unreliable near boundaries or with separation.
- coef_1_label
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- shr_1
- Models how predictors change the cumulative incidence of one event, through its subdistribution hazard.
- shr_1_low
- A range of effect values compatible with your data at the chosen confidence level.
- shr_1_high
- A range of effect values compatible with your data at the chosen confidence level.
- p_1
- How surprising your data would be if the null hypothesis were true, as a probability.
- epv
- Events (the rarer outcome) per estimated coefficient in logistic or Cox models.
- gray_chisq
- A sum of squared, scaled differences between observed and expected counts or estimates.
- gray_df
- How much independent information is left to estimate variability after fitting the model.
- gray_p
- Compares cumulative incidence curves between groups under competing risks; it asks how many events each group ends up with.
Per group, level or term: coef[<term>], se[<term>], naive_se[<term>], shr[<term>], shr_low[<term>], shr_high[<term>], z[<term>], p[<term>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-7). Python uses pandas, numpy, scipy, codesplash; R uses survival, cmprsk, nanoparquet, codesplashr.
Default traps between the two languages
- R builds the weighted data with survival::finegray and fits coxph(…, weight = fgwt, cluster = id); Python builds the same rows (censoring Kaplan–Meier, extended rows weighted G(t)/G(T)) and fits the same weighted partial likelihood with the same robust variance (codesplash.stats.survival_adv). Agreement ≈ 1e-12.
- cmprsk::crr fits the same model with its own tie and weight conventions; its estimates differ from finegray + coxph in the fourth decimal (Therneau's vignette). Gray's test agrees with cmprsk::cuminc to about 1e-13; see survival.cif for its tie factors and the singular case.
The exact script CodeSplash ran for example “Mgus pcm” · 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,
})
The exact script CodeSplash ran for example “Mgus pcm” · 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
))
Sources
- Fine, J. P., & Gray, R. J. (1999). A proportional hazards model for the subdistribution of a competing risk. JASA, 94, 496–509.
- Gray, R. J. (1988). A class of K-sample tests for comparing the cumulative incidence of a competing risk. Annals of Statistics, 16, 1141–1154.
- Therneau, T., Crowson, C., & Atkinson, E. (2024). Multi-state models and competing risks. survival package vignette.
From the CodeSplash method registry · survival.finegray v1.0.1.