FTime to event · survival.km
Kaplan–Meier survival curves
How long until the event happens, and does survival differ between groups?
Estimates the survival function with the Kaplan–Meier product-limit estimator (log–log intervals by default), the median survival time with its confidence limits, survival at chosen times with the number at risk, and optionally the restricted mean survival time. With a group it adds the log-rank test.
A real result
Example “Lung overall”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
median survival = 310
- Events
- 165
- Median survival
- 310
- 95% CI
- [284, 361]
Plots
View data
| upper | lower | Censored | At risk | Survival probability | time |
|---|---|---|---|---|---|
| 1 | 1 | 0 | 228 | 1 | 0 |
| 0.9994 | 0.9693 | 0 | 228 | 0.9956 | 5 |
| 0.9934 | 0.9539 | 0 | 227 | 0.9825 | 11 |
| 0.9908 | 0.9481 | 0 | 224 | 0.9781 | 12 |
| 0.9852 | 0.9367 | 0 | 223 | 0.9693 | 13 |
| 0.9823 | 0.9311 | 0 | 221 | 0.9649 | 15 |
| 0.9793 | 0.9255 | 0 | 220 | 0.9605 | 26 |
| 0.9762 | 0.9200 | 0 | 219 | 0.9561 | 30 |
| 0.9730 | 0.9146 | 0 | 218 | 0.9518 | 31 |
| 0.9665 | 0.9038 | 0 | 217 | 0.9430 | 53 |
| 0.9632 | 0.8985 | 0 | 215 | 0.9386 | 54 |
| 0.9598 | 0.8932 | 0 | 214 | 0.9342 | 59 |
| 0.9530 | 0.8828 | 0 | 213 | 0.9254 | 60 |
| 0.9495 | 0.8776 | 0 | 211 | 0.9211 | 61 |
| 0.9460 | 0.8725 | 0 | 210 | 0.9167 | 62 |
| 0.9390 | 0.8622 | 0 | 209 | 0.9079 | 65 |
| 0.9354 | 0.8572 | 0 | 207 | 0.9035 | 71 |
| 0.9318 | 0.8521 | 0 | 206 | 0.8991 | 79 |
| 0.9245 | 0.8420 | 0 | 205 | 0.8904 | 81 |
| 0.9172 | 0.8321 | 0 | 203 | 0.8816 | 88 |
| 0.9135 | 0.8271 | 1 | 201 | 0.8772 | 92 |
| 0.9098 | 0.8221 | 0 | 199 | 0.8728 | 93 |
| 0.9023 | 0.8122 | 0 | 198 | 0.8640 | 95 |
| 0.8985 | 0.8073 | 1 | 196 | 0.8596 | 105 |
| 0.8909 | 0.7974 | 0 | 194 | 0.8507 | 107 |
| 0.8871 | 0.7925 | 0 | 192 | 0.8463 | 110 |
| 0.8833 | 0.7876 | 0 | 191 | 0.8418 | 116 |
| 0.8794 | 0.7827 | 0 | 190 | 0.8374 | 118 |
| 0.8755 | 0.7778 | 0 | 189 | 0.8330 | 122 |
| 0.8717 | 0.7729 | 0 | 188 | 0.8285 | 131 |
| 0.8639 | 0.7632 | 0 | 187 | 0.8197 | 132 |
| 0.8600 | 0.7584 | 0 | 185 | 0.8153 | 135 |
| 0.8560 | 0.7536 | 0 | 184 | 0.8108 | 142 |
| 0.8521 | 0.7488 | 0 | 183 | 0.8064 | 144 |
| 0.8442 | 0.7392 | 0 | 182 | 0.7975 | 145 |
| 0.8403 | 0.7344 | 0 | 180 | 0.7931 | 147 |
| 0.8363 | 0.7296 | 0 | 179 | 0.7887 | 153 |
| 0.8283 | 0.7201 | 0 | 178 | 0.7798 | 156 |
| 0.8163 | 0.7058 | 0 | 176 | 0.7665 | 163 |
| 0.8083 | 0.6964 | 0 | 173 | 0.7577 | 166 |
| 0.8042 | 0.6917 | 0 | 171 | 0.7532 | 167 |
| 0.8002 | 0.6870 | 0 | 170 | 0.7488 | 170 |
| 0.8002 | 0.6870 | 1 | 169 | 0.7488 | 173 |
| 0.8002 | 0.6870 | 1 | 168 | 0.7488 | 174 |
| 0.7961 | 0.6822 | 1 | 167 | 0.7443 | 175 |
| 0.7920 | 0.6775 | 0 | 165 | 0.7398 | 176 |
| 0.7878 | 0.6727 | 1 | 164 | 0.7353 | 177 |
| 0.7795 | 0.6631 | 0 | 162 | 0.7262 | 179 |
| 0.7753 | 0.6583 | 0 | 160 | 0.7217 | 180 |
| 0.7669 | 0.6488 | 0 | 159 | 0.7126 | 181 |
| 0.7627 | 0.6440 | 0 | 157 | 0.7081 | 182 |
| 0.7585 | 0.6392 | 0 | 156 | 0.7035 | 183 |
| 0.7585 | 0.6392 | 1 | 155 | 0.7035 | 185 |
| 0.7543 | 0.6345 | 0 | 154 | 0.6989 | 186 |
| 0.7543 | 0.6345 | 1 | 153 | 0.6989 | 188 |
| 0.7500 | 0.6296 | 0 | 152 | 0.6943 | 189 |
| 0.7500 | 0.6296 | 1 | 151 | 0.6943 | 191 |
| 0.7500 | 0.6296 | 1 | 150 | 0.6943 | 192 |
| 0.7457 | 0.6248 | 0 | 149 | 0.6897 | 194 |
| 0.7457 | 0.6248 | 1 | 148 | 0.6897 | 196 |
First 60 of 187 rows.
View data
| Survival probability | time |
|---|---|
| 1 | 0 |
| 0.9956 | 5 |
| 0.9825 | 11 |
| 0.9781 | 12 |
| 0.9693 | 13 |
| 0.9649 | 15 |
| 0.9605 | 26 |
| 0.9561 | 30 |
| 0.9518 | 31 |
| 0.9430 | 53 |
| 0.9386 | 54 |
| 0.9342 | 59 |
| 0.9254 | 60 |
| 0.9211 | 61 |
| 0.9167 | 62 |
| 0.9079 | 65 |
| 0.9035 | 71 |
| 0.8991 | 79 |
| 0.8904 | 81 |
| 0.8816 | 88 |
| 0.8772 | 92 |
| 0.8728 | 93 |
| 0.8640 | 95 |
| 0.8596 | 105 |
| 0.8507 | 107 |
| 0.8463 | 110 |
| 0.8418 | 116 |
| 0.8374 | 118 |
| 0.8330 | 122 |
| 0.8285 | 131 |
| 0.8197 | 132 |
| 0.8153 | 135 |
| 0.8108 | 142 |
| 0.8064 | 144 |
| 0.7975 | 145 |
| 0.7931 | 147 |
| 0.7887 | 153 |
| 0.7798 | 156 |
| 0.7665 | 163 |
| 0.7577 | 166 |
| 0.7532 | 167 |
| 0.7488 | 170 |
| 0.7488 | 173 |
| 0.7488 | 174 |
| 0.7443 | 175 |
| 0.7398 | 176 |
| 0.7353 | 177 |
| 0.7262 | 179 |
| 0.7217 | 180 |
| 0.7126 | 181 |
| 0.7081 | 182 |
| 0.7035 | 183 |
| 0.7035 | 185 |
| 0.6989 | 186 |
| 0.6989 | 188 |
| 0.6943 | 189 |
| 0.6943 | 191 |
| 0.6943 | 192 |
| 0.6897 | 194 |
| 0.6897 | 196 |
First 60 of 187 rows.
View data
| Survival probability | time |
|---|---|
| 1 | 0 |
| 0.9956 | 5 |
| 0.9825 | 11 |
| 0.9781 | 12 |
| 0.9693 | 13 |
| 0.9649 | 15 |
| 0.9605 | 26 |
| 0.9561 | 30 |
| 0.9518 | 31 |
| 0.9430 | 53 |
| 0.9386 | 54 |
| 0.9342 | 59 |
| 0.9254 | 60 |
| 0.9211 | 61 |
| 0.9167 | 62 |
| 0.9079 | 65 |
| 0.9035 | 71 |
| 0.8991 | 79 |
| 0.8904 | 81 |
| 0.8816 | 88 |
| 0.8772 | 92 |
| 0.8728 | 93 |
| 0.8640 | 95 |
| 0.8596 | 105 |
| 0.8507 | 107 |
| 0.8463 | 110 |
| 0.8418 | 116 |
| 0.8374 | 118 |
| 0.8330 | 122 |
| 0.8285 | 131 |
| 0.8197 | 132 |
| 0.8153 | 135 |
| 0.8108 | 142 |
| 0.8064 | 144 |
| 0.7975 | 145 |
| 0.7931 | 147 |
| 0.7887 | 153 |
| 0.7798 | 156 |
| 0.7665 | 163 |
| 0.7577 | 166 |
| 0.7532 | 167 |
| 0.7488 | 170 |
| 0.7488 | 173 |
| 0.7488 | 174 |
| 0.7443 | 175 |
| 0.7398 | 176 |
| 0.7353 | 177 |
| 0.7262 | 179 |
| 0.7217 | 180 |
| 0.7126 | 181 |
| 0.7081 | 182 |
| 0.7035 | 183 |
| 0.7035 | 185 |
| 0.6989 | 186 |
| 0.6989 | 188 |
| 0.6943 | 189 |
| 0.6943 | 191 |
| 0.6943 | 192 |
| 0.6897 | 194 |
| 0.6897 | 196 |
First 60 of 187 rows.
Assumptions
- Non-informative censoring — 63 of 228 observations are censored; censoring must be unrelated to prognosis.
- Number of events — At least 10 events per curve.
Survival summary
| Curve | n | Events | Median | 95% CI low | 95% CI high | RMST (τ = 365) | SE |
|---|---|---|---|---|---|---|---|
| All | 228 | 165 | 310 | 284 | 361 | 263.22 | 7.799 |
Survival at chosen times
| Curve | Time | At risk | Survival | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| All | 100 | 196 | 0.8640 | 0.8122 | 0.9023 |
| All | 365 | 65 | 0.4092 | 0.3387 | 0.4784 |
| All | 730 | 13 | 0.1157 | 0.0676 | 0.1778 |
log-log intervals; Greenwood standard errors.
- Event: dead = true. Intervals: log-log transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley).
median survival = 310
- Events
- 165
- Median survival
- 310
- 95% CI
- [284, 361]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Non-informative censoring — 63 of 228 observations are censored; censoring must be unrelated to prognosis.
- Number of events — At least 10 events per curve.
Survival summary
| Curve | n | Events | Median | 95% CI low | 95% CI high | RMST (τ = 365) | SE |
|---|---|---|---|---|---|---|---|
| All | 228 | 165 | 310 | 284 | 361 | 263.22 | 7.799 |
Survival at chosen times
| Curve | Time | At risk | Survival | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| All | 100 | 196 | 0.8640 | 0.8122 | 0.9023 |
| All | 365 | 65 | 0.4092 | 0.3387 | 0.4784 |
| All | 730 | 13 | 0.1157 | 0.0676 | 0.1778 |
log-log intervals; Greenwood standard errors.
- Event: dead = true. Intervals: log-log transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley).
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 overalllung · event: dead · time: time
- Lung by sex numeric eventlung · event: status · group: sex · time: time
- Veteran celltype plainveteran · event: status · group: celltype · time: time
- Aml tiesaml · event: status · group: x · time: time
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
- Estimate survival: Kaplan–Meier · Statistics Guide · F — Time-to-event analysis
- Compare groups: log-rank · Statistics Guide · F — Time-to-event analysis
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.
- Groupscategorical / boolean · 0–1 column · 2–20 levels
- Optional — one curve per group and a log-rank test.
Choices you make
hypothesis
- Event leveldefault —
For a categorical event column, the level that marks the event (default the last level); other levels are censored.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
statistics
- Interval for the curvedefault log-log
Transformation for the pointwise intervals and the median's limits; the standard error is Greenwood's.
- Log–log (recommended)(default) — Builds the interval on the log–log scale; stays inside 0–1 and covers well in small samples.
- Log (survfit's default) — Builds the interval on the log scale; matches R's survfit, though its upper limit can hit 1.
- Plain (Greenwood, can leave [0, 1]) — Survival ± z·SE from Greenwood's formula; limits can leave 0–1, so use it only to match older work.
- Report survival at timesdefault
Times for the survival table (default 25%, 50% and 75% of the longest follow-up).
- Restricted mean up to τdefault 0
Restricted mean survival time up to this time (0 = off) — useful when hazards are not proportional.
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
Censored subjects must have the same prospects as those still followed; the data cannot test this.
Number of events
Curves and medians are unstable with few events per group.
What it reports
- Tests: Equal survival curves (log-rank)
- 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.
- median
- The time by which half the units have failed under the fitted model. Unlike the mean life, the far tail barely moves it.
- median_low
- A range of effect values compatible with your data at the chosen confidence level.
- median_high
- A range of effect values compatible with your data at the chosen confidence level.
- rmst
- The average event-free time up to a horizon τ, the area under the survival curve; a difference in RMST is a difference in time.
- rmst_se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- logrank_chisq
- A sum of squared, scaled differences between observed and expected counts or estimates.
- logrank_df
- How much independent information is left to estimate variability after fitting the model.
- logrank_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- event_label
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- n_groups
- How many independent units the analysis used; it sets precision and power.
Per group, level or term: n[<group>], events[<group>], median[<group>], median_low[<group>], median_high[<group>], rmst[<group>], rmst_se[<group>], surv[<group>@<time>], surv_low[<group>@<time>], surv_high[<group>@<time>], n_risk[<group>@<time>]
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
- Python computes the same quantities as survfit (Greenwood SE on the log scale, the same interval types, median rule and RMST) and survdiff in codesplash.stats.survival.
The exact script CodeSplash ran for example “Lung overall” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Kaplan–Meier survival curves
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.km 1.0.1 · spec 67e00adfab7af6ae
# 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
import codesplash as cs
from codesplash.stats import survival as sv # survfit/survdiff twins (see its docstring)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/lung.parquet", columns=["time", "dead"])
n_input = len(df)
df["dead"] = pd.Categorical(df["dead"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["time", "dead"]) # listwise deletion over the analysis columns
df["dead"] = df["dead"].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"]) # 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)
# %% Kaplan–Meier
conf = 0.95
conf_type = "log-log" # pinned: survfit's default is "log"
times = [100, 365, 730, ] or sv.default_times(t)
rmst_tau = 365 # 0 = no restricted mean
levels = []
strata = [("All", np.ones(len(t), dtype=bool))]
values = {"event_label": event_label, "n_groups": len(levels) if levels else None}
summary_rows, time_rows, curve = [], [], {"time": [], "surv": [], "low": [], "high": [], "strata": [], "nrisk": [], "ncensor": []}
for name, m in strata:
fit = sv.km(t[m], ev[m], conf=conf, conf_type=conf_type)
med, med_lo, med_hi = sv.km_median(fit)
rm, rm_se = sv.rmst(fit, rmst_tau) if rmst_tau > 0 else (None, None)
at = sv.km_at(fit, times)
nan = lambda x: None if x is None or not np.isfinite(x) else float(x) # noqa: E731
stats_ = {"n": float(m.sum()), "events": float(ev[m].sum()), "median": nan(med), "median_low": nan(med_lo),
"median_high": nan(med_hi), "rmst": nan(rm), "rmst_se": nan(rm_se)}
for k, v in stats_.items():
values[k if name == "All" else f"{k}[{name}]"] = v
summary_rows.append({"group": name, **stats_})
for i, x in enumerate(times):
key = f"{name}@{sv.key_num(x)}"
row = {"group": name, "time": x, "n_risk": float(at["n_risk"][i]), "surv": nan(at["surv"][i]),
"lower": nan(at["lower"][i]), "upper": nan(at["upper"][i])}
values[f"surv[{key}]"], values[f"surv_low[{key}]"], values[f"surv_high[{key}]"] = row["surv"], row["lower"], row["upper"]
values[f"n_risk[{key}]"] = row["n_risk"]
time_rows.append(row)
if (name == "All") == (not levels):
curve["time"] += [0.0] + fit["time"].tolist()
curve["surv"] += [1.0] + fit["surv"].tolist()
curve["low"] += [1.0] + [nan(x) for x in fit["lower"]]
curve["high"] += [1.0] + [nan(x) for x in fit["upper"]]
curve["strata"] += [name] * (len(fit["time"]) + 1)
curve["nrisk"] += [float(m.sum())] + fit["n_risk"].tolist()
curve["ncensor"] += [0.0] + fit["n_censor"].tolist()
# %% Log-rank test
if levels:
codes = np.array([levels.index(x) for x in gv])
lr = sv.logrank(t, ev, codes, rho=0.0) # survdiff(Surv(time, event) ~ group)
values.update({"logrank_chisq": lr["chisq"], "logrank_df": float(lr["df"]), "logrank_p": lr["p"]})
else:
values.update({"logrank_chisq": None, "logrank_df": None, "logrank_p": None})
# %% Assumptions
assumptions = [{"key": "censoring", "label": "Non-informative censoring", "status": "info",
"detail": f"{int((~ev).sum())} of {len(ev)} observations are censored; censoring must be unrelated to prognosis."}]
few = [r["group"] for r in summary_rows if r["events"] < 10 and (r["group"] != "All" or not levels)]
if few:
assumptions.append({"key": "sample_size", "label": "Number of events", "status": "warn",
"detail": f"Fewer than 10 events in {', '.join(few)}; medians and curves are imprecise."})
else:
assumptions.append({"key": "sample_size", "label": "Number of events", "status": "pass", "detail": "At least 10 events per curve."})
# %% Result
pct = f"{conf:.0%}"
med_text = "not reached" if values["median"] is None else f"{values['median']:.4g}"
cs.publish({
"method": "survival.km",
"methodVersion": "1.0.1",
"title": "Kaplan–Meier survival" + (f" by {g}" if levels else ""),
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(len(t)),
"summary": f"{int(ev.sum())} of {len(t)} subjects had the event ({event_label}); median survival {med_text}."
+ (f" Log-rank {cs.fmt_p(values['logrank_p'])}." if levels else ""),
"apa": f"median survival = {med_text}" + (f"; log-rank χ²({values['logrank_df']:.0f}) = {cs.fmt_num(values['logrank_chisq'])}, {cs.fmt_p(values['logrank_p'])}" if levels else ""),
"statistics": [
{"key": "events", "label": "Events", "value": values["events"], "format": "integer"},
{"key": "median", "label": "Median survival", "value": values["median"]},
{"key": "median_ci", "label": f"{pct} CI", "value": [values["median_low"], values["median_high"]]},
] + ([{"key": "logrank_p", "label": "Log-rank p", "value": values["logrank_p"], "format": "p"}] if levels else []),
"tables": [
{"key": "summary", "title": "Survival summary", "columns": [
{"key": "group", "label": g if levels else "Curve", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "events", "label": "Events", "type": "integer"}, {"key": "median", "label": "Median", "type": "number"},
{"key": "median_low", "label": f"{pct} CI low", "type": "number"}, {"key": "median_high", "label": f"{pct} CI high", "type": "number"},
] + ([{"key": "rmst", "label": f"RMST (τ = {rmst_tau:g})", "type": "number"}, {"key": "rmst_se", "label": "SE", "type": "number"}]
if rmst_tau > 0 else []), "rows": summary_rows},
{"key": "survival_at", "title": "Survival at chosen times", "columns": [
{"key": "group", "label": g if levels else "Curve", "type": "string"}, {"key": "time", "label": "Time", "type": "number"},
{"key": "n_risk", "label": "At risk", "type": "integer"}, {"key": "surv", "label": "Survival", "type": "number"},
{"key": "lower", "label": f"{pct} CI low", "type": "number"}, {"key": "upper", "label": f"{pct} CI high", "type": "number"},
], "rows": time_rows, "note": f"{conf_type} intervals; Greenwood standard errors."},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {event_label}. Intervals: {conf_type} transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley)."],
"charts": [cs.chart("km", "km-curve", "Kaplan–Meier curve" + (f" by {g}" if levels else ""), {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"low": cs.col("lower", curve["low"], "numeric"), "high": cs.col("upper", curve["high"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels) if levels else None,
"nrisk": cs.col("At risk", curve["nrisk"], "numeric"), "ncensor": cs.col("Censored", curve["ncensor"], "numeric"),
}), cs.chart("cumhaz", "cumhaz", "Cumulative hazard" + (f" by {g}" if levels else ""), {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels) if levels else None,
}), cs.chart("loglog", "loglog-survival", "Log–log survival" + (f" by {g}" if levels else ""), {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels) if levels else None,
})],
"values": values,
})
The exact script CodeSplash ran for example “Lung overall” · R version 4.5.1 (2025-06-13)
# Kaplan–Meier survival curves
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.km 1.0.1 · spec 67e00adfab7af6ae
# 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")))
n_input <- nrow(df)
df[["dead"]] <- factor(df[["dead"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("time", "dead")]), , 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")) # 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)
# %% Kaplan–Meier
conf <- 0.95
conf_type <- "log-log" # pinned: survfit's default is "log"
times <- c(100, 365, 730)
if (length(times) == 0) times <- cs_default_times(tt)
rmst_tau <- 365 # 0 = no restricted mean
levels_g <- character(0)
strata <- list(All = rep(TRUE, length(tt)))
fin <- function(x) if (length(x) == 0 || is.null(x) || !is.finite(x)) NA else unname(x)
values <- list(event_label = event_label, n_groups = if (length(levels_g)) length(levels_g) else NA)
summary_rows <- list()
time_rows <- list()
curve <- list(time = numeric(0), surv = numeric(0), low = numeric(0), high = numeric(0), strata = character(0),
nrisk = numeric(0), ncensor = numeric(0))
for (name in names(strata)) {
m <- strata[[name]]
fit <- survfit(Surv(tt[m], ev[m]) ~ 1, conf.type = conf_type, conf.int = conf)
tb <- summary(fit, rmean = if (rmst_tau > 0) rmst_tau else "none")$table
st <- list(n = sum(m), events = sum(ev[m]), median = fin(tb[["median"]]),
median_low = fin(tb[[grep("LCL$", names(tb))]]), median_high = fin(tb[[grep("UCL$", names(tb))]]),
rmst = if (rmst_tau > 0) fin(tb[["rmean"]]) else NA, rmst_se = if (rmst_tau > 0) fin(tb[["se(rmean)"]]) else NA)
for (k in names(st)) values[[if (name == "All") k else sprintf("%s[%s]", k, name)]] <- st[[k]]
summary_rows[[length(summary_rows) + 1]] <- c(list(group = name), st)
s_at <- cs_step_at(fit$time, fit$surv, times)
l_at <- cs_step_at(fit$time, fit$lower, times)
u_at <- cs_step_at(fit$time, fit$upper, times)
r_at <- cs_n_risk_at(tt[m], times)
for (i in seq_along(times)) {
key <- sprintf("%s@%s", name, cs_key_num(times[i]))
values[[sprintf("surv[%s]", key)]] <- fin(s_at[i])
values[[sprintf("surv_low[%s]", key)]] <- fin(l_at[i])
values[[sprintf("surv_high[%s]", key)]] <- fin(u_at[i])
values[[sprintf("n_risk[%s]", key)]] <- r_at[i]
time_rows[[length(time_rows) + 1]] <- list(group = name, time = times[i], n_risk = r_at[i], surv = fin(s_at[i]),
lower = fin(l_at[i]), upper = fin(u_at[i]))
}
if ((name == "All") == (length(levels_g) == 0)) {
curve$time <- c(curve$time, 0, fit$time)
curve$surv <- c(curve$surv, 1, fit$surv)
curve$low <- c(curve$low, 1, fit$lower)
curve$high <- c(curve$high, 1, fit$upper)
curve$strata <- c(curve$strata, rep(name, length(fit$time) + 1))
curve$nrisk <- c(curve$nrisk, sum(m), fit$n.risk)
curve$ncensor <- c(curve$ncensor, 0, fit$n.censor)
}
}
# %% Log-rank test
if (length(levels_g)) {
lr <- survdiff(Surv(tt, ev) ~ gv, rho = 0)
lr_df <- sum(lr$n > 0) - 1
values$logrank_chisq <- lr$chisq
values$logrank_df <- lr_df
values$logrank_p <- stats::pchisq(lr$chisq, lr_df, lower.tail = FALSE)
} else {
values$logrank_chisq <- NA
values$logrank_df <- NA
values$logrank_p <- NA
}
# %% Assumptions
assumptions <- list(list(key = "censoring", label = "Non-informative censoring", status = "info",
detail = sprintf("%d of %d observations are censored; censoring must be unrelated to prognosis.",
sum(!ev), length(ev))))
few <- character(0)
for (r in summary_rows) if (r$events < 10 && (r$group != "All" || length(levels_g) == 0)) few <- c(few, r$group)
assumptions[[2]] <- if (length(few)) {
list(key = "sample_size", label = "Number of events", status = "warn",
detail = sprintf("Fewer than 10 events in %s; medians and curves are imprecise.", paste(few, collapse = ", ")))
} else {
list(key = "sample_size", label = "Number of events", status = "pass", detail = "At least 10 events per curve.")
}
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
med_text <- if (is.na(values$median)) "not reached" else format(signif(values$median, 4))
summary_cols <- list(
list(key = "group", label = if (length(levels_g)) g else "Curve", type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "events", label = "Events", type = "integer"), list(key = "median", label = "Median", type = "number"),
list(key = "median_low", label = paste(pct, "CI low"), type = "number"), list(key = "median_high", label = paste(pct, "CI high"), type = "number")
)
if (rmst_tau > 0) summary_cols <- c(summary_cols, list(list(key = "rmst", label = sprintf("RMST (τ = %s)", format(rmst_tau)), type = "number"),
list(key = "rmst_se", label = "SE", type = "number")))
cs_publish(list(
method = "survival.km",
methodVersion = "1.0.1",
title = paste0("Kaplan–Meier survival", if (length(levels_g)) paste(" by", g) else ""),
engine = cs_engine_info("survival", "codesplashr"),
n = length(tt),
summary = paste0(sprintf("%d of %d subjects had the event (%s); median survival %s.", sum(ev), length(ev), event_label, med_text),
if (length(levels_g)) sprintf(" Log-rank %s.", cs_fmt_p(values$logrank_p)) else ""),
apa = paste0("median survival = ", med_text,
if (length(levels_g)) sprintf("; log-rank χ²(%d) = %s, %s", values$logrank_df, cs_fmt_num(values$logrank_chisq), cs_fmt_p(values$logrank_p)) else ""),
statistics = c(list(
list(key = "events", label = "Events", value = values$events, format = "integer"),
list(key = "median", label = "Median survival", value = values$median),
list(key = "median_ci", label = paste(pct, "CI"), value = c(values$median_low, values$median_high))
), if (length(levels_g)) list(list(key = "logrank_p", label = "Log-rank p", value = values$logrank_p, format = "p"))),
tables = list(
list(key = "summary", title = "Survival summary", columns = summary_cols, rows = summary_rows),
list(key = "survival_at", title = "Survival at chosen times", columns = list(
list(key = "group", label = if (length(levels_g)) g else "Curve", type = "string"), list(key = "time", label = "Time", type = "number"),
list(key = "n_risk", label = "At risk", type = "integer"), list(key = "surv", label = "Survival", type = "number"),
list(key = "lower", label = paste(pct, "CI low"), type = "number"), list(key = "upper", label = paste(pct, "CI high"), type = "number")
), rows = time_rows, note = paste(conf_type, "intervals; Greenwood standard errors."))
),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Event: %s. Intervals: %s transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley).", event_label, conf_type)),
charts = list(cs_chart("km", "km-curve", paste0("Kaplan–Meier curve", if (length(levels_g)) paste(" by", g) else ""), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
low = cs_col("lower", curve$low, "numeric"), high = cs_col("upper", curve$high, "numeric"),
strata = if (length(levels_g)) cs_col(g, curve$strata, "categorical", levels = levels_g) else NULL,
nrisk = cs_col("At risk", curve$nrisk, "numeric"), ncensor = cs_col("Censored", curve$ncensor, "numeric")
)), cs_chart("cumhaz", "cumhaz", paste0("Cumulative hazard", if (length(levels_g)) paste(" by", g) else ""), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
strata = if (length(levels_g)) cs_col(g, curve$strata, "categorical", levels = levels_g) else NULL
)), cs_chart("loglog", "loglog-survival", paste0("Log–log survival", if (length(levels_g)) paste(" by", g) else ""), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
strata = if (length(levels_g)) cs_col(g, curve$strata, "categorical", levels = levels_g) else NULL
))),
values = values
))
Sources
- Kaplan, E. L., & Meier, P. (1958). Nonparametric estimation from incomplete observations. JASA, 53, 457–481.
- Brookmeyer, R., & Crowley, J. (1982). A confidence interval for the median survival time. Biometrics, 38, 29–41.
- Royston, P., & Parmar, M. K. B. (2013). Restricted mean survival time. BMC Medical Research Methodology, 13, 152.
From the CodeSplash method registry · survival.km v1.0.1.