Skip to content

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.

Verified in Python and R Python and R agree to 10 decimals

A real result

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

Kaplan–Meier survivalRecorded · Python and R agreeRecorded 2026-11-17 · 24 values compared
R

median survival = 310

Events
165
Median survival
310
95% CI
[284, 361]

Plots

Kaplan–Meier curveWhat fraction survives (is event-free) over time, and do groups differ?
View data
upperlowerCensoredAt riskSurvival probabilitytime
11022810
0.99940.969302280.99565
0.99340.953902270.982511
0.99080.948102240.978112
0.98520.936702230.969313
0.98230.931102210.964915
0.97930.925502200.960526
0.97620.920002190.956130
0.97300.914602180.951831
0.96650.903802170.943053
0.96320.898502150.938654
0.95980.893202140.934259
0.95300.882802130.925460
0.94950.877602110.921161
0.94600.872502100.916762
0.93900.862202090.907965
0.93540.857202070.903571
0.93180.852102060.899179
0.92450.842002050.890481
0.91720.832102030.881688
0.91350.827112010.877292
0.90980.822101990.872893
0.90230.812201980.864095
0.89850.807311960.8596105
0.89090.797401940.8507107
0.88710.792501920.8463110
0.88330.787601910.8418116
0.87940.782701900.8374118
0.87550.777801890.8330122
0.87170.772901880.8285131
0.86390.763201870.8197132
0.86000.758401850.8153135
0.85600.753601840.8108142
0.85210.748801830.8064144
0.84420.739201820.7975145
0.84030.734401800.7931147
0.83630.729601790.7887153
0.82830.720101780.7798156
0.81630.705801760.7665163
0.80830.696401730.7577166
0.80420.691701710.7532167
0.80020.687001700.7488170
0.80020.687011690.7488173
0.80020.687011680.7488174
0.79610.682211670.7443175
0.79200.677501650.7398176
0.78780.672711640.7353177
0.77950.663101620.7262179
0.77530.658301600.7217180
0.76690.648801590.7126181
0.76270.644001570.7081182
0.75850.639201560.7035183
0.75850.639211550.7035185
0.75430.634501540.6989186
0.75430.634511530.6989188
0.75000.629601520.6943189
0.75000.629611510.6943191
0.75000.629611500.6943192
0.74570.624801490.6897194
0.74570.624811480.6897196

First 60 of 187 rows.

Cumulative hazardHow has risk built up over time?
View data
Survival probabilitytime
10
0.99565
0.982511
0.978112
0.969313
0.964915
0.960526
0.956130
0.951831
0.943053
0.938654
0.934259
0.925460
0.921161
0.916762
0.907965
0.903571
0.899179
0.890481
0.881688
0.877292
0.872893
0.864095
0.8596105
0.8507107
0.8463110
0.8418116
0.8374118
0.8330122
0.8285131
0.8197132
0.8153135
0.8108142
0.8064144
0.7975145
0.7931147
0.7887153
0.7798156
0.7665163
0.7577166
0.7532167
0.7488170
0.7488173
0.7488174
0.7443175
0.7398176
0.7353177
0.7262179
0.7217180
0.7126181
0.7081182
0.7035183
0.7035185
0.6989186
0.6989188
0.6943189
0.6943191
0.6943192
0.6897194
0.6897196

First 60 of 187 rows.

Log–log survivalAre the hazards proportional, and could the times be Weibull?
View data
Survival probabilitytime
10
0.99565
0.982511
0.978112
0.969313
0.964915
0.960526
0.956130
0.951831
0.943053
0.938654
0.934259
0.925460
0.921161
0.916762
0.907965
0.903571
0.899179
0.890481
0.881688
0.877292
0.872893
0.864095
0.8596105
0.8507107
0.8463110
0.8418116
0.8374118
0.8330122
0.8285131
0.8197132
0.8153135
0.8108142
0.8064144
0.7975145
0.7931147
0.7887153
0.7798156
0.7665163
0.7577166
0.7532167
0.7488170
0.7488173
0.7488174
0.7443175
0.7398176
0.7353177
0.7262179
0.7217180
0.7126181
0.7081182
0.7035183
0.7035185
0.6989186
0.6989188
0.6943189
0.6943191
0.6943192
0.6897194
0.6897196

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

CurvenEventsMedian95% CI low95% CI highRMST (τ = 365)SE
All228165310284361263.227.799

Survival at chosen times

CurveTimeAt riskSurvival95% CI low95% CI high
All1001960.86400.81220.9023
All365650.40920.33870.4784
All730130.11570.06760.1778

log-log intervals; Greenwood standard errors.

  • Event: dead = true. Intervals: log-log transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley).
Python

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

CurvenEventsMedian95% CI low95% CI highRMST (τ = 365)SE
All228165310284361263.227.799

Survival at chosen times

CurveTimeAt riskSurvival95% CI low95% CI high
All1001960.86400.81220.9023
All365650.40920.33870.4784
All730130.11570.06760.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.
Python

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

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.