Skip to content

FTime to event · survival.cox

Cox proportional hazards regression

Which factors are associated with the hazard of the event?

Fits a Cox proportional hazards model (Efron ties by default, optional strata) and reports hazard ratios with confidence intervals, the likelihood-ratio, Wald and score tests, Harrell's concordance (apparent, with its standard error and an optional bootstrap optimism correction), AIC and BIC, the Grambsch–Therneau test of proportional hazards for each term with scaled Schoenfeld residuals, martingale residuals for functional form, Cox–Snell residuals for overall fit and DFBETA influence.

Verified in Python and R Python and R agree to 6 decimals Seeded

A real result

Example “Lung age sex”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Cox proportional hazards modelRecorded · Python and R agreeRecorded 2026-11-17 · 54 values compared
R

HR = 1.02, 95% CI [1.00, 1.04], p = .065

Likelihood-ratio χ²
14.123
df
2
p
< .001
Concordance (C, apparent)
0.6029
AIC
1489.70

Effect size

  • Hazard ratio (age) 1.017 95% CI [0.9990, 1.036]

Plots

Hazard ratiosHow large are several estimates, how precise, and which exclude the null?
View data
Hazard ratioupperTermlower
1.0171.036age0.9990
0.59860.8311sex: female0.4311
Scaled Schoenfeld residualsDoes a Cox model coefficient change over time (proportional-hazards check)?
View data
β(t)Termtime
0.0404age5
0.1537age11
0.2519age11
0.0554age11
0.1555age12
0.1848age13
0.0304age13
0.0874age15
0.1440age26
0.1308age30
0.2719age31
−0.0209age53
0.0773age53
0.1336age54
0.1484age59
0.0511age60
0.0230age60
−0.0751age61
0.0509age62
−0.0050age65
0.0792age65
−0.0329age71
0.0370age79
−0.1738age81
−0.1457age81
−0.0766age88
0.0497age88
−0.1751age92
0.1609age93
0.2041age95
−0.1047age95
−0.0063age105
−0.0197age107
0.0084age107
0.0223age110
0.1907age116
0.1079age118
0.0103age122
−0.1722age131
−0.0754age132
−0.3141age132
−0.0348age135
0.0070age142
0.0630age144
−0.0210age145
−0.1193age145
−0.0215age147
0.1608age153
0.0490age156
−0.1054age156
0.0910age163
0.1331age163
−0.1196age163
−0.0208age166
0.1196age166
−0.2452age167
−0.0776age170
0.1464age175
0.1472age176
−0.0481age177

First 60 of 330 rows.

Martingale residuals by predictor (functional form)Is a predictor's effect really a straight line?
View data
Martingale residualPredictorPredictor value
0.0044age74
−0.5058age68
−3.130age56
0.5328age57
−2.351age60
−4.254age74
0.4475age68
0.2900age71
0.5483age53
0.6806age61
0.6856age57
−0.4190age68
−0.7272age68
0.8848age60
−0.6192age57
0.7233age67
−1.185age70
−1.558age63
0.9479age56
0.8665age57
0.1622age67
0.9359age49
−0.5980age50
−0.0266age58
−0.3860age72
−0.0548age70
−0.7475age60
0.7603age70
0.0150age53
0.9685age74
0.0266age69
0.9435age73
−0.2934age48
0.8916age60
0.9353age61
0.8710age62
−2.367age65
−2.222age66
0.8035age74
−0.6731age64
−0.6209age70
0.7975age73
0.2836age59
0.8473age60
−1.055age68
0.8715age76
0.0392age74
−0.5306age63
−1.548age74
−0.4247age50
−0.9904age72
0.5596age63
0.9271age68
0.4257age58
−1.235age59
0.8894age62
0.9968age65
0.7875age57
−0.2735age58
0.4314age64

First 60 of 228 rows.

Cox–Snell residuals on exponential paperDo these failures fall on a straight line on this family's probability paper?
View data
EventSeriesUnit exponential F(r)Cox–Snell residual
1data—0.9956
1data—1.506
0data—3.130
1data—0.4672
1data—3.351
0data—4.254
1data—0.5525
1data—0.7100
1data—0.4517
1data—0.3194
1data—0.3144
1data—1.419
1data—1.727
1data—0.1152
1data—1.619
1data—0.2767
1data—2.185
1data—2.558
1data—0.0521
1data—0.1335
1data—0.8378
1data—0.0641
1data—1.598
1data—1.027
1data—1.386
1data—1.055
1data—1.748
1data—0.2397
1data—0.9850
1data—0.0315
1data—0.9734
1data—0.0565
1data—1.293
1data—0.1084
1data—0.0647
1data—0.1290
1data—3.367
0data—2.222
1data—0.1965
1data—1.673
1data—1.621
1data—0.2025
1data—0.7164
1data—0.1527
1data—2.055
1data—0.1285
1data—0.9608
1data—1.531
1data—2.548
1data—1.425
1data—1.990
1data—0.4404
1data—0.0729
1data—0.5743
1data—2.235
1data—0.1106
1data—0.0032
1data—0.2125
1data—1.273
1data—0.5686

First 60 of 288 rows.

Assumptions

  • Proportional hazards — Global Grambsch–Therneau χ²(2) = 2.77, p = .250; no evidence that hazard ratios change over time.
  • Events per variable — 82.5 events per coefficient.
  • Non-informative censoring — 63 of 228 observations are censored.
  • Functional form — Not tested: look at the martingale residuals against age. A smooth that bends away from zero suggests a transformation or a spline.
  • Influential observations — Largest |DFBETAS| = 0.42; 18 of 228 subjects above 2/√n = 0.13.

Hazard ratios

TermβSEHR95% CI low95% CI highzp
age0.01700.00921.0170.99901.0361.848.065
sex: female−0.51320.16750.59860.43110.8311−3.065.002

Overall tests

Testχ²dfp
Likelihood ratio14.1232< .001
Wald13.4732.001
Score (log-rank)13.7222.001

Proportional-hazards test (Grambsch–Therneau)

Termχ²dfp
age0.20921.647
sex2.6081.106
Global2.7712.250

Score test for a log-hazard ratio that changes linearly in 1 − KM(t) (cox.zph, transform = "km").

Model fit

MeasureValue95% CI low95% CI highNote
Concordance (C, apparent)0.60290.55290.6528Harrell's C on the data the model was fitted to; SE 0.0255 (infinitesimal jackknife).
AIC1489.70——−2 log partial likelihood + 2k.
BIC1495.91——−2 log partial likelihood + k·log(events), events = 165.

The apparent C is optimistic for new data; the bootstrap option estimates by how much.

Most influential subjects

RowTerm most affectedDFBETADFBETASMartingale residual
6age−0.0039−0.4236−4.254
85age0.00360.3922−2.239
38sex: female−0.0436−0.2604−2.222
68sex: female−0.0379−0.2265−1.981
3age0.00190.2079−3.130
89age0.00190.2061−1.235
74age−0.0017−0.18270.8410
71sex: female0.02920.1746−3.254
129age−0.0016−0.1712−1.298
149age0.00140.15410.9190

Row = position among the analyzed rows. DFBETA is the approximate change in the coefficient if the row were left out; DFBETAS divides it by the coefficient's SE.

  • Event: dead = true. Ties: efron.
Python

HR = 1.02, 95% CI [1.00, 1.04], p = .065

Likelihood-ratio χ²
14.123
df
2
p
< .001
Concordance (C, apparent)
0.6029
AIC
1489.70

Effect size

  • Hazard ratio (age) 1.017 95% CI [0.9990, 1.036]

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Proportional hazards — Global Grambsch–Therneau χ²(2) = 2.77, p = .250; no evidence that hazard ratios change over time.
  • Events per variable — 82.5 events per coefficient.
  • Non-informative censoring — 63 of 228 observations are censored.
  • Functional form — Not tested: look at the martingale residuals against age. A smooth that bends away from zero suggests a transformation or a spline.
  • Influential observations — Largest |DFBETAS| = 0.42; 18 of 228 subjects above 2/√n = 0.13.

Hazard ratios

TermβSEHR95% CI low95% CI highzp
age0.01700.00921.0170.99901.0361.848.065
sex: female−0.51320.16750.59860.43110.8311−3.065.002

Overall tests

Testχ²dfp
Likelihood ratio14.1232< .001
Wald13.4732.001
Score (log-rank)13.7222.001

Proportional-hazards test (Grambsch–Therneau)

Termχ²dfp
age0.20921.647
sex2.6081.106
Global2.7712.250

Score test for a log-hazard ratio that changes linearly in 1 − KM(t) (cox.zph, transform = "km").

Model fit

MeasureValue95% CI low95% CI highNote
Concordance (C, apparent)0.60290.55290.6528Harrell's C on the data the model was fitted to; SE 0.0255 (infinitesimal jackknife).
AIC1489.70——−2 log partial likelihood + 2k.
BIC1495.91——−2 log partial likelihood + k·log(events), events = 165.

The apparent C is optimistic for new data; the bootstrap option estimates by how much.

Most influential subjects

RowTerm most affectedDFBETADFBETASMartingale residual
6age−0.0039−0.4236−4.254
85age0.00360.3922−2.239
38sex: female−0.0436−0.2604−2.222
68sex: female−0.0379−0.2265−1.981
3age0.00190.2079−3.130
89age0.00190.2061−1.235
74age−0.0017−0.18270.8410
71sex: female0.02920.1746−3.254
129age−0.0016−0.1712−1.298
149age0.00140.15410.9190

Row = position among the analyzed rows. DFBETA is the approximate change in the coefficient if the row were left out; DFBETAS divides it by the coefficient's SE.

  • Event: dead = true. 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

  • Lung age sexlung · event: dead · predictors: age, sex · time: time
  • Lung ecog space breslowlung · event: status · predictors: age, ph ecog, wt loss · time: time
  • Veteran factors strataveteran · event: status · predictors: trt, karno, prior · strata: celltype · time: time
  • Veteran celltypeveteran · event: status · predictors: celltype, age · time: time
  • Lung age sex validatelung · event: dead · predictors: age, sex, ph ecog · time: time
  • Degenerate constantlung · event: dead · predictors: age, sex · time: time
  • Degenerate single levellung · event: dead · predictors: age, sex · time: time

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Time-to-event: Cox, survival models · Statistics Guide · D — Predict an outcome
  • Model predictors: Cox PH · Statistics Guide · F — Time-to-event analysis
  • Check assumptions: Schoenfeld residuals · Statistics Guide · F — Time-to-event analysis
  • Model-specific checks (VIF, PH, PO, dispersion) · Statistics Guide · Step 2 — Check assumptions
  • Regression (linear, logistic, Poisson) · DS & ML Decision Guide · Predict — forecast or classify outcomes

What you need

Timenumeric · 1 column
Follow-up time until the event or censoring (zero or positive).
Eventboolean / numeric / categorical · 1 column
Whether the event happened. Yes/no, 0/1 or 1/2 codes (the larger code is the event), or a category chosen below.
Predictorsnumeric / categorical / boolean · 1–20 columns · 2–30 levels
Covariates. Categorical predictors use treatment contrasts against their first stored level.
Stratacategorical / boolean · 0–1 column · 2–50 levels
Optional — a separate baseline hazard per stratum (no hazard ratio is estimated for it).

Choices you make

hypothesis

Event leveldefault —

For a categorical event column, the level that marks the event (default the last 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 (recommended; coxph's default)(default) — Approximates the likelihood for tied times more closely; the usual choice.
  • Breslow (SAS/Stata's default) — Uses a plainer approximation; matches SAS and Stata defaults, and is less accurate with many ties.
Concordance validationdefault none

The apparent concordance is optimistic for new data. The bootstrap estimate refits the model many times, so it takes longer.

  • Apparent only(default) — Harrell's C on the data the model was fitted to, with its standard error.
  • Bootstrap optimism correction (Harrell) — Refits the model on bootstrap resamples to estimate how much the apparent C overstates performance on new data, and subtracts it.
Bootstrap resamplesdefault 200

Number of bootstrap refits for the optimism correction (the shared random stream gives the same resamples in Python and R). Resamples that miss a level or have no events are skipped.

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 hazards

    Hazard ratios constant over time — Grambsch–Therneau test on scaled Schoenfeld residuals (cox.zph, Kaplan–Meier time scale).

    • If violated → Accelerated failure time model (log-normal) — Log-normal and log-logistic AFT models do not assume proportional hazards; alternatively stratify by the offending variable or report restricted mean survival. Changes the question: Time ratios (how much longer survival lasts) instead of hazard ratios.
    • If violated → Stratify by {failed} — A separate baseline hazard for each level of the predictor whose effect changes over time. Its hazard ratio is no longer estimated; the other hazard ratios are adjusted for it. Changes the question: No hazard ratio for the stratifying variable.
  • Events per variable

    At least about 10 events per estimated coefficient for stable estimates.

  • Non-informative censoring

    Censoring must be unrelated to prognosis given the covariates.

  • Functional form

    Each numeric predictor enters the log hazard as a straight line — martingale residuals against the predictor should show no trend.

  • Influential observations

    No single subject should move a coefficient by more than about one standard error (|DFBETAS| > 1); 2/√n flags subjects worth a look.

What it reports

  • Tests: Model likelihood-ratio test
  • Tests: First predictor's hazard ratio
n
How many independent units the analysis used; it sets precision and power.
events
In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.
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.
score_chisq
A sum of squared, scaled differences between observed and expected counts or estimates.
score_p
How surprising your data would be if the null hypothesis were true, as a probability.
concordance
The share of usable pairs where the person with the higher predicted risk has the event first. 0.5 is chance.
ph_chisq
A sum of squared, scaled differences between observed and expected counts or estimates.
ph_p
How surprising your data would be if the null hypothesis were true, as a probability.
coef_1_label
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
hr_1
The ratio of instantaneous event rates between groups; 0.7 means a 30% lower rate at any moment.
hr_1_low
A range of effect values compatible with your data at the chosen confidence level.
hr_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.
event_label
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
aic
A model score balancing fit against complexity; lower is better, and only differences matter.
bic
Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
concordance_se
The typical size of the error in an estimate, the standard deviation of its sampling distribution.
concordance_low
A range of effect values compatible with your data at the chosen confidence level.
concordance_high
A range of effect values compatible with your data at the chosen confidence level.
max_abs_dfbetas
The biggest standardized change in any coefficient when one subject is left out; above 1 marks an influential subject.
n_influential
How many independent units the analysis used; it sets precision and power.
martingale_min
Smallest and largest martingale residuals (observed minus expected events); very negative values are long survivors the model missed.
martingale_max
Smallest and largest martingale residuals (observed minus expected events); very negative values are long survivors the model missed.
optimism
How much the apparent C-index overstates performance on new data, estimated by refitting on bootstrap resamples.
concordance_corrected
The apparent C-index minus the bootstrap optimism: a fairer guess of how well the model ranks new subjects.
boot_used
Resamples that refitted cleanly for the optimism correction; the same ones are skipped in both engines.

Per group, level or term: coef[<term>], se[<term>], hr[<term>], hr_low[<term>], hr_high[<term>], z[<term>], p[<term>], ph_chisq[<predictor>], ph_p[<predictor>], dfbetas_max[<term>]

Python and R

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

Default traps between the two languages

  • Both engines maximize the same partial likelihood by Newton's method (Python: statsmodels PHReg likelihood; R: coxph with eps = 1e-12); agreement ≈ 1e-9.
  • Python computes the PH test and Harrell's C in codesplash.stats.survival, checked against cox.zph(transform = "km") and survival::concordance.
  • Python computes the concordance's infinitesimal-jackknife variance and the martingale and score residuals (dfbeta = score · covariance) in codesplash.stats.survival; R uses concordance()$var and residuals.coxph. The bootstrap uses the shared Wichmann–Hill resamples, skipping resamples without events or with a constant or collinear design column in both engines.
Python

The exact script CodeSplash ran for example “Lung age sex” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Cox proportional hazards regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cox 1.1.0 · spec be108a13077d2af0
# Dataset: lung (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  # Cox fit, proportional-hazards test, concordance

# %% Data
df = pd.read_parquet("tests/parity/fixtures/lung.parquet", columns=["time", "dead", "age", "sex"])
n_input = len(df)
df["dead"] = pd.Categorical(df["dead"], categories=["false", "true"])  # stored level order
df["sex"] = pd.Categorical(df["sex"], categories=["male", "female"])  # stored level order
df = df.dropna(subset=["time", "dead", "age", "sex"])  # listwise deletion over the analysis columns
df["dead"] = df["dead"].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, ["time", "dead", "age", "sex"])  # infinite values stop the run (registry/errors.yaml)

# %% Event coding
tcol = "time"
ecol = "dead"
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()))
event_level = "true"  # the event; other levels are censored
ev = (df[ecol].astype(str) == event_level).to_numpy()
event_label = f"{ecol} = {event_level}"
if not ev.any():
    cs.cs_error("CS_E_NO_EVENTS", event=event_label)

# %% Design matrix (treatment contrasts against the first stored level)
preds = ["age", "sex"]
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)

# %% Cox model
conf = 0.95
ties = "efron"  # pinned: coxph's default is Efron, SAS/Stata use Breslow
sname = None
scodes = None
fit = sv.cox_fit(t, ev, X, strata=scodes, ties=ties)
beta = fit["coef"]
se = np.sqrt(np.diag(fit["cov"]))
z = beta / se
pv = 2 * stats.norm.sf(np.abs(z))
q = stats.norm.ppf(1 - (1 - conf) / 2)
hr, hr_lo, hr_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))
conc = sv.concordance(t, ev, X @ beta, strata=scodes)["concordance"]
one_time = np.unique(t[ev]).size < 2  # with every event at one time the proportional-hazards test is undefined
if one_time:
    warnings.append(cs.cs_warning("CS_W_TIES", column=tcol, consequence="every event happened at the same time, so the proportional-hazards test is not computed."))
    zph = {"global": (None, None, None), "terms": [(None, None, None) for _ in preds], "times": np.zeros(0), "scaled": np.zeros((0, k))}
else:
    zph = sv.cox_zph(t, ev, X, beta, terms, strata=scodes, ties=ties)
ph_chisq, _, ph_p = zph["global"]

# %% Fit measures and the apparent concordance
aic = -2 * fit["loglik"] + 2 * k
bic = -2 * fit["loglik"] + k * np.log(ev.sum())  # n = the number of events, as R's BIC() for coxph
cvar = sv.concordance_var(t, ev, X @ beta, strata=scodes)  # infinitesimal-jackknife SE, as survival::concordance()
c_se = cvar["se"]
c_lo, c_hi = (max(0.0, conc - q * c_se), min(1.0, conc + q * c_se)) if np.isfinite(conc) and np.isfinite(c_se) else (None, None)

# %% Residuals: martingale (functional form), Cox–Snell (overall fit) and dfbeta (influence)
res = sv.cox_residuals(t, ev, X, beta, strata=scodes, ties=ties)
mart = res["martingale"]
cox_snell = ev - mart
dfb = res["score"] @ fit["cov"]  # one-step change in each coefficient when the row is left out
dfbs = dfb / se
abs_dfbs = np.abs(dfbs)
infl_cut = 2 / np.sqrt(len(t))
n_infl = int((abs_dfbs.max(axis=1) > infl_cut).sum())
max_dfbs = float(abs_dfbs.max())
num_preds = [pname for pname, idx in zip(preds, terms) if len(idx) == 1 and not isinstance(df[pname].dtype, pd.CategoricalDtype)
             and not pd.api.types.is_bool_dtype(df[pname]) and df[pname].nunique() > 2]
optimism = c_corrected = None
boot_used = 0

values = {
    "n": float(len(t)), "events": float(ev.sum()), "n_coef": float(k), "loglik": fit["loglik"], "loglik0": fit["loglik0"],
    "lr_chisq": fit["lr"], "lr_df": float(k), "lr_p": lr_p,
    "wald_chisq": fit["wald"], "wald_p": float(stats.chi2.sf(fit["wald"], k)),
    "score_chisq": fit["score"], "score_p": float(stats.chi2.sf(fit["score"], k)),
    "concordance": conc, "ph_chisq": ph_chisq, "ph_p": ph_p,
    "coef_1_label": labels[0], "hr_1": float(hr[0]), "hr_1_low": float(hr_lo[0]), "hr_1_high": float(hr_hi[0]), "p_1": float(pv[0]),
    "epv": float(ev.sum()) / k, "event_label": event_label,
    "aic": float(aic), "bic": float(bic), "concordance_se": float(c_se), "concordance_low": c_lo, "concordance_high": c_hi,
    "max_abs_dfbetas": max_dfbs, "n_influential": float(n_infl), "martingale_min": float(mart.min()), "martingale_max": float(mart.max()),
    "optimism": optimism, "concordance_corrected": c_corrected, "boot_used": float(boot_used),
}
coef_rows = []
for i, lab in enumerate(labels):
    for key, val in (("coef", beta[i]), ("se", se[i]), ("hr", hr[i]), ("hr_low", hr_lo[i]), ("hr_high", hr_hi[i]), ("z", z[i]), ("p", pv[i])):
        values[f"{key}[{lab}]"] = float(val)
    values[f"dfbetas_max[{lab}]"] = float(abs_dfbs[:, i].max())
    coef_rows.append({"term": lab, "coef": float(beta[i]), "se": float(se[i]), "hr": float(hr[i]), "hr_low": float(hr_lo[i]),
                      "hr_high": float(hr_hi[i]), "z": float(z[i]), "p": float(pv[i])})
ph_rows = []
for pname, (c2, dfree, pp) in zip(preds, zph["terms"]):
    values[f"ph_chisq[{pname}]"], values[f"ph_p[{pname}]"] = c2, pp
    ph_rows.append({"term": pname, "chisq": c2, "df": None if dfree is None else float(dfree), "p": pp})
ph_rows.append({"term": "Global", "chisq": ph_chisq, "df": float(k), "p": ph_p})

# %% Assumptions
bad = [r["term"] for r in ph_rows[:-1] if r["p"] is not None and r["p"] < 0.05]
if one_time:
    ph_check = {"key": "proportional_hazards", "label": "Proportional hazards", "status": "info", "detail": "Not tested: every event happened at the same time."}
else:
    ph_check = {"key": "proportional_hazards", "label": "Proportional hazards", "status": "warn" if ph_p < 0.05 or bad else "pass",
                "statistic": ph_chisq, "p": ph_p,
                "detail": f"Global Grambsch–Therneau χ²({k}) = {ph_chisq:.2f}, {cs.fmt_p(ph_p)}"
                + (f"; time-varying effect for {', '.join(bad)}. Consider stratifying by {'it' if len(bad) == 1 else 'them'}, a time-varying"
                   " effect (Cox model with time-varying covariates), an accelerated failure time model or restricted mean survival."
                   if bad else "; no evidence that hazard ratios change over time.")}
assumptions = [
    ph_check,
    {"key": "events_per_variable", "label": "Events per variable", "status": "warn" if values["epv"] < 10 else "pass",
     "detail": f"{values['epv']:.1f} events per coefficient" + (" — fewer than 10; estimates may be biased and unstable." if values["epv"] < 10 else ".")},
    {"key": "censoring", "label": "Non-informative censoring", "status": "info", "detail": f"{int((~ev).sum())} of {len(ev)} observations are censored."},
    {"key": "functional_form", "label": "Functional form", "status": "info",
     "detail": (f"Not tested: look at the martingale residuals against {', '.join(num_preds)}. A smooth that bends away from zero"
                " suggests a transformation or a spline." if num_preds else "No numeric predictor with more than two values to check.")},
    {"key": "influence", "label": "Influential observations", "status": "warn" if max_dfbs > 1 else "pass", "statistic": max_dfbs,
     "detail": f"Largest |DFBETAS| = {max_dfbs:.2f}; {n_infl} of {len(t)} subjects above 2/√n = {infl_cut:.2f}"
     + (". At least one subject moves a coefficient by more than one standard error." if max_dfbs > 1 else ".")},
]

# %% Charts: hazard ratios and scaled Schoenfeld residuals
rows_sch = np.arange(len(zph["times"]))
if len(rows_sch) * k > 5000:
    rows_sch = np.unique(np.round(np.linspace(0, len(rows_sch) - 1, max(5000 // k, 2))).astype(int))
sch_time, sch_res, sch_term = [], [], []
for i, lab in enumerate(labels):
    sch_time += zph["times"][rows_sch].tolist()
    sch_res += zph["scaled"][rows_sch, i].tolist()
    sch_term += [lab] * len(rows_sch)

# %% Charts: martingale residuals by numeric predictor, Cox–Snell residuals on exponential paper
mart_x, mart_r, mart_term = [], [], []
if num_preds:
    rows_m = np.arange(len(t))
    if len(rows_m) * len(num_preds) > 5000:
        rows_m = np.unique(np.round(np.linspace(0, len(t) - 1, max(5000 // len(num_preds), 2))).astype(int))
    for pname in num_preds:
        mart_x += df[pname].to_numpy(dtype=float)[rows_m].tolist()
        mart_r += mart[rows_m].tolist()
        mart_term += [pname] * len(rows_m)
rows_cs = np.arange(len(t))
if len(rows_cs) > 5000:
    rows_cs = np.unique(np.round(np.linspace(0, len(t) - 1, 5000)).astype(int))
cs_fit = np.linspace(0.0, float(cox_snell.max()), 61)[1:] if cox_snell.max() > 0 else np.zeros(0)

# %% Influence: the subjects with the largest scaled dfbeta
top = np.lexsort((np.arange(len(t)), -abs_dfbs.max(axis=1)))[:10]
infl_rows = []
for r in top:
    j = int(np.argmax(abs_dfbs[r]))
    infl_rows.append({"row": float(r + 1), "term": labels[j], "dfbeta": float(dfb[r, j]), "dfbetas": float(dfbs[r, j]), "martingale": float(mart[r])})

# %% Result
pct = f"{conf:.0%}"
fit_rows = [
    {"measure": "Concordance (C, apparent)", "value": conc, "low": c_lo, "high": c_hi,
     "note": f"Harrell's C on the data the model was fitted to; SE {c_se:.4f} (infinitesimal jackknife)."},
    {"measure": "AIC", "value": float(aic), "low": None, "high": None, "note": "−2 log partial likelihood + 2k."},
    {"measure": "BIC", "value": float(bic), "low": None, "high": None, "note": f"−2 log partial likelihood + k·log(events), events = {int(ev.sum())}."},
]
if c_corrected is not None:
    fit_rows.insert(1, {"measure": "Concordance (optimism-corrected)", "value": c_corrected, "low": None, "high": None,
                        "note": f"Apparent C minus the mean optimism {optimism:.4f} over {boot_used} bootstrap refits (Harrell)."})
cs.publish({
    "method": "survival.cox",
    "methodVersion": "1.1.0",
    "title": "Cox proportional hazards model",
    "engine": cs.engine_info("numpy", "scipy", "statsmodels", "codesplash"),
    "n": int(len(t)),
    "summary": f"Cox model ({int(ev.sum())} events): likelihood-ratio χ²({k}) = {fit['lr']:.2f}, {cs.fmt_p(lr_p)}; apparent concordance {conc:.3f}.",
    "apa": f"HR = {cs.fmt_num(hr[0])}, {pct} CI [{cs.fmt_num(hr_lo[0])}, {cs.fmt_num(hr_hi[0])}], {cs.fmt_p(pv[0])}",
    "statistics": [
        {"key": "lr_chisq", "label": "Likelihood-ratio χ²", "value": fit["lr"]}, {"key": "lr_df", "label": "df", "value": float(k), "format": "integer"},
        {"key": "lr_p", "label": "p", "value": lr_p, "format": "p"}, {"key": "concordance", "label": "Concordance (C, apparent)", "value": conc},
        {"key": "aic", "label": "AIC", "value": float(aic)},
    ],
    "tables": [
        {"key": "coefficients", "title": "Hazard ratios", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "coef", "label": "β", "type": "number"},
            {"key": "se", "label": "SE", "type": "number"}, {"key": "hr", "label": "HR", "type": "number"},
            {"key": "hr_low", "label": f"{pct} CI low", "type": "number"}, {"key": "hr_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": "Overall 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": [
            {"test": "Likelihood ratio", "chisq": fit["lr"], "df": float(k), "p": lr_p},
            {"test": "Wald", "chisq": fit["wald"], "df": float(k), "p": values["wald_p"]},
            {"test": "Score (log-rank)", "chisq": fit["score"], "df": float(k), "p": values["score_p"]},
        ]},
        {"key": "proportional_hazards", "title": "Proportional-hazards test (Grambsch–Therneau)", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "chisq", "label": "χ²", "type": "number"},
            {"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"},
        ], "rows": ph_rows, "note": "Score test for a log-hazard ratio that changes linearly in 1 − KM(t) (cox.zph, transform = \"km\")."},
        {"key": "fit", "title": "Model fit", "columns": [
            {"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
            {"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"},
            {"key": "note", "label": "Note", "type": "string"},
        ], "rows": fit_rows, "note": "The apparent C is optimistic for new data; the bootstrap option estimates by how much."},
        {"key": "influence", "title": "Most influential subjects", "columns": [
            {"key": "row", "label": "Row", "type": "integer"}, {"key": "term", "label": "Term most affected", "type": "string"},
            {"key": "dfbeta", "label": "DFBETA", "type": "number"}, {"key": "dfbetas", "label": "DFBETAS", "type": "number"},
            {"key": "martingale", "label": "Martingale residual", "type": "number"},
        ], "rows": infl_rows, "note": "Row = position among the analyzed rows. DFBETA is the approximate change in the coefficient if the row were left out; DFBETAS divides it by the coefficient's SE."},
    ],
    "effectSizes": [{"key": "hr_1", "label": f"Hazard ratio ({labels[0]})", "value": float(hr[0]), "ciLow": float(hr_lo[0]),
                     "ciHigh": float(hr_hi[0]), "ciLevel": conf, "method": "Wald interval on log(HR)"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Event: {event_label}. Ties: {ties}." + (f" Stratified by {sname}." if sname else "")],
    "charts": [
        cs.chart("hr", "forest", "Hazard ratios", {
            "label": cs.col("Term", labels, "categorical", levels=labels), "estimate": cs.col("Hazard ratio", hr, "numeric"),
            "low": cs.col("lower", hr_lo, "numeric"), "high": cs.col("upper", hr_hi, "numeric"),
        }, controls={"reference": 1, "log": True}),
        cs.chart("schoenfeld", "schoenfeld", "Scaled Schoenfeld residuals", {
            "time": cs.col(tcol, sch_time, "numeric"), "residual": cs.col("β(t)", sch_res, "numeric"),
            "term": cs.col("Term", sch_term, "categorical", levels=labels),
        }),
        *([cs.chart("martingale", "component-residual", "Martingale residuals by predictor (functional form)", {
            "x": cs.col("Predictor value", mart_x, "numeric"), "partial": cs.col("Martingale residual", mart_r, "numeric"),
            "term": cs.col("Predictor", mart_term, "categorical", levels=num_preds),
        }, controls={"smooth": True})] if num_preds else []),
        cs.chart("cox_snell", "probability-plot", "Cox–Snell residuals on exponential paper", {
            "time": cs.col("Cox–Snell residual", np.concatenate((cox_snell[rows_cs], cs_fit)), "numeric"),
            "event": cs.col("Event", np.concatenate((ev[rows_cs].astype(float), np.full(cs_fit.size, np.nan))), "numeric"),
            "fit": cs.col("Unit exponential F(r)", np.concatenate((np.full(rows_cs.size, np.nan), -np.expm1(-cs_fit))), "numeric"),
            "family": cs.col("Series", ["data"] * rows_cs.size + ["unit exponential"] * cs_fit.size, "categorical", levels=["data", "unit exponential"]),
        }, controls={"paper": "exponential"}),
    ],
    "values": values,
})
R

The exact script CodeSplash ran for example “Lung age sex” · R version 4.5.1 (2025-06-13)

# Cox proportional hazards regression
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cox 1.1.0 · spec be108a13077d2af0
# Dataset: lung (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/lung.parquet", col_select = c("time", "dead", "age", "sex")))
n_input <- nrow(df)
df[["dead"]] <- factor(df[["dead"]], levels = c("false", "true"))  # stored level order
df[["sex"]] <- factor(df[["sex"]], levels = c("male", "female"))  # stored level order
df <- df[stats::complete.cases(df[c("time", "dead", "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("time", "dead", "age", "sex"))  # infinite values stop the run (registry/errors.yaml)

# %% Event coding
tcol <- "time"
ecol <- "dead"
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))
event_level <- "true"  # the event; other levels are censored
ev <- as.character(df[[ecol]]) == event_level
event_label <- sprintf("%s = %s", ecol, event_level)
if (!any(ev)) cs_error("CS_E_NO_EVENTS", event = event_label)

# %% Predictors (treatment contrasts against the first stored level)
preds <- c("age", "sex")
dd <- data.frame(.t = tt, .e = ev)
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 <- paste(sprintf("`%s`", gsub("`", "\\\\`", preds)), collapse = " + ")

# %% Cox model
conf <- 0.95
ties <- "efron"  # pinned: coxph's default is Efron, SAS/Stata use Breslow
sname <- NULL
fit <- coxph(stats::as.formula(paste("Surv(.t, .e) ~", rhs)), data = dd, ties = ties,
             control = coxph.control(eps = 1e-12, toler.chol = 1e-15, iter.max = 60))
beta <- unname(coef(fit))
if (anyNA(beta)) stop("Some coefficients could not be estimated (collinear predictors).")
V <- unname(vcov(fit))
se <- sqrt(diag(V))
z <- beta / se
pv <- 2 * stats::pnorm(-abs(z))
q <- stats::qnorm(1 - (1 - conf) / 2)
hr <- exp(beta)
hr_lo <- exp(beta - q * se)
hr_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))
score <- unname(fit$score)
cc <- concordance(fit)  # var: infinitesimal-jackknife variance of C
conc <- unname(cc$concordance)
one_time <- length(unique(tt[ev])) < 2  # with every event at one time the proportional-hazards test is undefined
if (one_time) {
  warnings <- c(warnings, cs_warning("CS_W_TIES", column = tcol, consequence = "every event happened at the same time, so the proportional-hazards test is not computed."))
  zph <- NULL
  zt <- matrix(NA_real_, length(preds) + 1, 3)
} else {
  zph <- cox.zph(fit, transform = "km")
  zt <- unname(zph$table)
}
ph_chisq <- zt[nrow(zt), 1]
ph_p <- zt[nrow(zt), 3]

# %% Fit measures and the apparent concordance
aic <- -2 * fit$loglik[2] + 2 * k
bic <- -2 * fit$loglik[2] + k * log(sum(ev))  # n = the number of events, as BIC() for coxph
c_se <- sqrt(unname(cc$var))
ci_ok <- is.finite(conc) && is.finite(c_se)
c_lo <- if (ci_ok) max(0, conc - q * c_se) else NA_real_
c_hi <- if (ci_ok) min(1, conc + q * c_se) else NA_real_

# %% Residuals: martingale (functional form), Cox–Snell (overall fit) and dfbeta (influence)
mart <- unname(residuals(fit, type = "martingale"))
cox_snell <- ev - mart
dfb <- unname(as.matrix(residuals(fit, type = "dfbeta")))  # one-step change in each coefficient when the row is left out
dfbs <- sweep(dfb, 2, se, "/")
abs_dfbs <- abs(dfbs)
infl_cut <- 2 / sqrt(length(tt))
n_infl <- sum(apply(abs_dfbs, 1, max) > infl_cut)
max_dfbs <- max(abs_dfbs)
num_preds <- preds[vapply(preds, function(p) is.numeric(df[[p]]) && length(unique(df[[p]])) > 2, logical(1))]
optimism <- NA_real_
c_corrected <- NA_real_
boot_used <- 0

values <- list(
  n = length(tt), events = sum(ev), 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),
  score_chisq = score, score_p = stats::pchisq(score, k, lower.tail = FALSE),
  concordance = conc, ph_chisq = ph_chisq, ph_p = ph_p,
  coef_1_label = labels[1], hr_1 = hr[1], hr_1_low = hr_lo[1], hr_1_high = hr_hi[1], p_1 = pv[1],
  epv = sum(ev) / k, event_label = event_label,
  aic = aic, bic = bic, concordance_se = c_se, concordance_low = c_lo, concordance_high = c_hi,
  max_abs_dfbetas = max_dfbs, n_influential = n_infl, martingale_min = min(mart), martingale_max = max(mart),
  optimism = optimism, concordance_corrected = c_corrected, boot_used = boot_used
)
coef_rows <- list()
for (i in seq_along(labels)) {
  lab <- labels[i]
  vals <- list(coef = beta[i], se = se[i], hr = hr[i], hr_low = hr_lo[i], hr_high = hr_hi[i], z = z[i], p = pv[i])
  for (key in names(vals)) values[[sprintf("%s[%s]", key, lab)]] <- vals[[key]]
  values[[sprintf("dfbetas_max[%s]", lab)]] <- max(abs_dfbs[, i])
  coef_rows[[i]] <- c(list(term = lab), vals)
}
ph_rows <- list()
for (i in seq_along(preds)) {
  values[[sprintf("ph_chisq[%s]", preds[i])]] <- zt[i, 1]
  values[[sprintf("ph_p[%s]", preds[i])]] <- zt[i, 3]
  ph_rows[[i]] <- list(term = preds[i], chisq = zt[i, 1], df = zt[i, 2], p = zt[i, 3])
}
ph_rows[[length(ph_rows) + 1]] <- list(term = "Global", chisq = ph_chisq, df = k, p = ph_p)

# %% Assumptions
bad <- preds[which(zt[seq_along(preds), 3] < 0.05)]
ph_check <- if (one_time) {
  list(key = "proportional_hazards", label = "Proportional hazards", status = "info", detail = "Not tested: every event happened at the same time.")
} else {
  list(key = "proportional_hazards", label = "Proportional hazards", status = if (ph_p < 0.05 || length(bad)) "warn" else "pass",
       statistic = ph_chisq, p = ph_p,
       detail = paste0(sprintf("Global Grambsch–Therneau χ²(%d) = %.2f, %s", k, ph_chisq, cs_fmt_p(ph_p)),
                       if (length(bad)) sprintf(paste0("; time-varying effect for %s. Consider stratifying by %s, a time-varying",
                                                       " effect (Cox model with time-varying covariates), an accelerated failure time model or restricted mean survival."),
                                                paste(bad, collapse = ", "), if (length(bad) == 1) "it" else "them")
                       else "; no evidence that hazard ratios change over time."))
}
assumptions <- list(
  ph_check,
  list(key = "events_per_variable", label = "Events per variable", status = if (values$epv < 10) "warn" else "pass",
       detail = paste0(sprintf("%.1f events per coefficient", values$epv),
                       if (values$epv < 10) " — fewer than 10; estimates may be biased and unstable." else ".")),
  list(key = "censoring", label = "Non-informative censoring", status = "info",
       detail = sprintf("%d of %d observations are censored.", sum(!ev), length(ev))),
  list(key = "functional_form", label = "Functional form", status = "info",
       detail = if (length(num_preds)) sprintf(paste0("Not tested: look at the martingale residuals against %s. A smooth that bends away from zero",
                                                      " suggests a transformation or a spline."), paste(num_preds, collapse = ", "))
                else "No numeric predictor with more than two values to check."),
  list(key = "influence", label = "Influential observations", status = if (max_dfbs > 1) "warn" else "pass", statistic = max_dfbs,
       detail = paste0(sprintf("Largest |DFBETAS| = %.2f; %d of %d subjects above 2/√n = %.2f", max_dfbs, n_infl, length(tt), infl_cut),
                       if (max_dfbs > 1) ". At least one subject moves a coefficient by more than one standard error." else "."))
)

# %% Charts: hazard ratios and scaled Schoenfeld residuals
sch <- if (one_time) matrix(numeric(0), 0, k) else as.matrix(zph$y)
sch_times <- if (one_time) numeric(0) else zph$time
rows_sch <- seq_len(nrow(sch))
if (length(rows_sch) * k > 5000) rows_sch <- unique(round(seq(1, nrow(sch), length.out = max(5000 %/% k, 2))))
sch_time <- rep(sch_times[rows_sch], k)
sch_res <- as.vector(sch[rows_sch, , drop = FALSE])
sch_term <- rep(labels, each = length(rows_sch))

# %% Charts: martingale residuals by numeric predictor, Cox–Snell residuals on exponential paper
mart_x <- numeric(0)
mart_r <- numeric(0)
mart_term <- character(0)
if (length(num_preds)) {
  rows_m <- seq_along(tt)
  if (length(rows_m) * length(num_preds) > 5000) rows_m <- unique(round(seq(1, length(tt), length.out = max(5000 %/% length(num_preds), 2))))
  for (pname in num_preds) {
    mart_x <- c(mart_x, as.numeric(df[[pname]])[rows_m])
    mart_r <- c(mart_r, mart[rows_m])
    mart_term <- c(mart_term, rep(pname, length(rows_m)))
  }
}
rows_cs <- seq_along(tt)
if (length(rows_cs) > 5000) rows_cs <- unique(round(seq(1, length(tt), length.out = 5000)))
cs_fit <- if (max(cox_snell) > 0) seq(0, max(cox_snell), length.out = 61)[-1] else numeric(0)

# %% Influence: the subjects with the largest scaled dfbeta
row_max <- apply(abs_dfbs, 1, max)
top <- head(order(-row_max, seq_along(row_max)), 10)
infl_rows <- lapply(top, function(r) {
  j <- which.max(abs_dfbs[r, ])
  list(row = r, term = labels[j], dfbeta = dfb[r, j], dfbetas = dfbs[r, j], martingale = mart[r])
})

# %% Result
pct <- sprintf("%.0f%%", conf * 100)
fit_rows <- list(
  list(measure = "Concordance (C, apparent)", value = conc, low = c_lo, high = c_hi,
       note = sprintf("Harrell's C on the data the model was fitted to; SE %.4f (infinitesimal jackknife).", c_se)),
  list(measure = "AIC", value = aic, low = NA_real_, high = NA_real_, note = "−2 log partial likelihood + 2k."),
  list(measure = "BIC", value = bic, low = NA_real_, high = NA_real_, note = sprintf("−2 log partial likelihood + k·log(events), events = %d.", sum(ev)))
)
if (!is.na(c_corrected)) {
  fit_rows <- append(fit_rows, list(list(measure = "Concordance (optimism-corrected)", value = c_corrected, low = NA_real_, high = NA_real_,
                                         note = sprintf("Apparent C minus the mean optimism %.4f over %d bootstrap refits (Harrell).", optimism, boot_used))), after = 1)
}
cs_publish(list(
  method = "survival.cox",
  methodVersion = "1.1.0",
  title = "Cox proportional hazards model",
  engine = cs_engine_info("survival", "codesplashr"),
  n = length(tt),
  summary = sprintf("Cox model (%d events): likelihood-ratio χ²(%d) = %.2f, %s; apparent concordance %.3f.", sum(ev), k, lr, cs_fmt_p(lr_p), conc),
  apa = sprintf("HR = %s, %s CI [%s, %s], %s", cs_fmt_num(hr[1]), pct, cs_fmt_num(hr_lo[1]), cs_fmt_num(hr_hi[1]), cs_fmt_p(pv[1])),
  statistics = list(
    list(key = "lr_chisq", label = "Likelihood-ratio χ²", value = lr), list(key = "lr_df", label = "df", value = k, format = "integer"),
    list(key = "lr_p", label = "p", value = lr_p, format = "p"), list(key = "concordance", label = "Concordance (C, apparent)", value = conc),
    list(key = "aic", label = "AIC", value = aic)
  ),
  tables = list(
    list(key = "coefficients", title = "Hazard ratios", columns = list(
      list(key = "term", label = "Term", type = "string"), list(key = "coef", label = "β", type = "number"),
      list(key = "se", label = "SE", type = "number"), list(key = "hr", label = "HR", type = "number"),
      list(key = "hr_low", label = paste(pct, "CI low"), type = "number"), list(key = "hr_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 = "Overall 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 = list(
      list(test = "Likelihood ratio", chisq = lr, df = k, p = lr_p),
      list(test = "Wald", chisq = wald, df = k, p = values$wald_p),
      list(test = "Score (log-rank)", chisq = score, df = k, p = values$score_p)
    )),
    list(key = "proportional_hazards", title = "Proportional-hazards test (Grambsch–Therneau)", columns = list(
      list(key = "term", label = "Term", type = "string"), list(key = "chisq", label = "χ²", type = "number"),
      list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")
    ), rows = ph_rows, note = "Score test for a log-hazard ratio that changes linearly in 1 − KM(t) (cox.zph, transform = \"km\")."),
    list(key = "fit", title = "Model fit", columns = list(
      list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
      list(key = "low", label = paste(pct, "CI low"), type = "number"), list(key = "high", label = paste(pct, "CI high"), type = "number"),
      list(key = "note", label = "Note", type = "string")
    ), rows = fit_rows, note = "The apparent C is optimistic for new data; the bootstrap option estimates by how much."),
    list(key = "influence", title = "Most influential subjects", columns = list(
      list(key = "row", label = "Row", type = "integer"), list(key = "term", label = "Term most affected", type = "string"),
      list(key = "dfbeta", label = "DFBETA", type = "number"), list(key = "dfbetas", label = "DFBETAS", type = "number"),
      list(key = "martingale", label = "Martingale residual", type = "number")
    ), rows = infl_rows, note = "Row = position among the analyzed rows. DFBETA is the approximate change in the coefficient if the row were left out; DFBETAS divides it by the coefficient's SE.")
  ),
  effectSizes = list(list(key = "hr_1", label = sprintf("Hazard ratio (%s)", labels[1]), value = hr[1], ciLow = hr_lo[1],
                          ciHigh = hr_hi[1], ciLevel = conf, method = "Wald interval on log(HR)")),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(sprintf("Event: %s. Ties: %s.", event_label, ties), if (!is.null(sname)) sprintf(" Stratified by %s.", sname) else "")),
  charts = list(
    cs_chart("hr", "forest", "Hazard ratios", list(
      label = cs_col("Term", labels, "categorical", levels = labels), estimate = cs_col("Hazard ratio", hr, "numeric"),
      low = cs_col("lower", hr_lo, "numeric"), high = cs_col("upper", hr_hi, "numeric")
    ), controls = list(reference = 1, log = TRUE)),
    cs_chart("schoenfeld", "schoenfeld", "Scaled Schoenfeld residuals", list(
      time = cs_col(tcol, sch_time, "numeric"), residual = cs_col("β(t)", sch_res, "numeric"),
      term = cs_col("Term", sch_term, "categorical", levels = labels)
    )),
    if (length(num_preds)) cs_chart("martingale", "component-residual", "Martingale residuals by predictor (functional form)", list(
      x = cs_col("Predictor value", mart_x, "numeric"), partial = cs_col("Martingale residual", mart_r, "numeric"),
      term = cs_col("Predictor", mart_term, "categorical", levels = num_preds)
    ), controls = list(smooth = TRUE)),
    cs_chart("cox_snell", "probability-plot", "Cox–Snell residuals on exponential paper", list(
      time = cs_col("Cox–Snell residual", c(cox_snell[rows_cs], cs_fit), "numeric"),
      event = cs_col("Event", c(as.numeric(ev[rows_cs]), rep(NA_real_, length(cs_fit))), "numeric"),
      fit = cs_col("Unit exponential F(r)", c(rep(NA_real_, length(rows_cs)), -expm1(-cs_fit)), "numeric"),
      family = cs_col("Series", c(rep("data", length(rows_cs)), rep("unit exponential", length(cs_fit))), "categorical",
                      levels = c("data", "unit exponential"))
    ), controls = list(paper = "exponential"))
  ),
  values = values
))

Sources

  • Cox, D. R. (1972). Regression models and life-tables. JRSS B, 34, 187–220.
  • Efron, B. (1977). The efficiency of Cox's likelihood function for censored data. JASA, 72, 557–565.
  • Grambsch, P. M., & Therneau, T. M. (1994). Proportional hazards tests and diagnostics based on weighted residuals. Biometrika, 81, 515–526.
  • Harrell, F. E., Lee, K. L., & Mark, D. B. (1996). Multivariable prognostic models. Statistics in Medicine, 15, 361–387.
  • Therneau, T. M., Grambsch, P. M., & Fleming, T. R. (1990). Martingale-based residuals for survival models. Biometrika, 77, 147–160.
  • Cox, D. R., & Snell, E. J. (1968). A general definition of residuals. JRSS B, 30, 248–275.
  • Therneau, T. M., & Atkinson, E. (2024). The concordance statistic. Vignette of the survival package.

From the CodeSplash method registry · survival.cox v1.1.0.