FTime to event · survival.recurrent
Recurrent events (mean cumulative function, Andersen–Gill, PWP, WLW)
How often do repeated events occur over time, and which factors change their rate?
Analyses events that can happen more than once per subject (infections, hospital admissions, relapses) from start–stop data. The mean cumulative function (MCF) estimates the expected number of events per subject over time, with Lawless–Nadeau robust intervals. Regression models: Andersen–Gill (a common rate for every event), Prentice–Williams–Peterson total-time or gap-time (a separate baseline for the first, second, … event) and Wei–Lin–Weissfeld marginal models, all with robust standard errors clustered by subject.
A real result
Example “Cgd ag group”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
RR = 0.33, 95% CI [0.18, 0.60], p < .001
- Events
- 76
- Events per subject
- 0.5938
- Robust Wald χ²
- 16.620
- p
- < .001
Effect size
- Rate ratio (treat: rIFN-g) 0.3263 95% CI [0.1777, 0.5989]
Plots
View data
| treat | upper | lower | Mean events per subject | tstop |
|---|---|---|---|---|
| placebo | 0 | 0 | 0 | 0 |
| placebo | 0.0453 | −0.0145 | 0.0154 | 4 |
| placebo | 0.0728 | −0.0112 | 0.0308 | 6 |
| placebo | 0.0972 | −0.0049 | 0.0462 | 8 |
| placebo | 0.1200 | 0.0031 | 0.0615 | 11 |
| placebo | 0.1417 | 0.0121 | 0.0769 | 14 |
| placebo | 0.1627 | 0.0219 | 0.0923 | 18 |
| placebo | 0.1831 | 0.0323 | 0.1077 | 19 |
| placebo | 0.2136 | 0.0325 | 0.1231 | 22 |
| placebo | 0.2326 | 0.0443 | 0.1385 | 23 |
| placebo | 0.2603 | 0.0474 | 0.1538 | 26 |
| placebo | 0.2785 | 0.0599 | 0.1692 | 52 |
| placebo | 0.2966 | 0.0727 | 0.1846 | 57 |
| placebo | 0.3221 | 0.0779 | 0.2000 | 65 |
| placebo | 0.3397 | 0.0911 | 0.2154 | 67 |
| placebo | 0.3570 | 0.1045 | 0.2308 | 91 |
| placebo | 0.3749 | 0.1184 | 0.2466 | 99 |
| placebo | 0.3749 | 0.1184 | 0.2466 | 102 |
| placebo | 0.3931 | 0.1325 | 0.2628 | 104 |
| placebo | 0.4110 | 0.1468 | 0.2789 | 120 |
| placebo | 0.4600 | 0.1623 | 0.3112 | 121 |
| placebo | 0.4774 | 0.1771 | 0.3273 | 146 |
| placebo | 0.5069 | 0.1800 | 0.3434 | 152 |
| placebo | 0.5297 | 0.1894 | 0.3595 | 159 |
| placebo | 0.5467 | 0.2046 | 0.3757 | 168 |
| placebo | 0.5744 | 0.2093 | 0.3918 | 169 |
| placebo | 0.5911 | 0.2247 | 0.4079 | 175 |
| placebo | 0.5911 | 0.2247 | 0.4079 | 192 |
| placebo | 0.5911 | 0.2247 | 0.4079 | 195 |
| placebo | 0.5911 | 0.2247 | 0.4079 | 198 |
| placebo | 0.5911 | 0.2247 | 0.4079 | 200 |
| placebo | 0.6204 | 0.2300 | 0.4252 | 203 |
| placebo | 0.6392 | 0.2468 | 0.4430 | 206 |
| placebo | 0.6392 | 0.2468 | 0.4430 | 207 |
| placebo | 0.6583 | 0.2641 | 0.4612 | 211 |
| placebo | 0.6881 | 0.2707 | 0.4794 | 213 |
| placebo | 0.7073 | 0.2885 | 0.4979 | 226 |
| placebo | 0.7073 | 0.2885 | 0.4979 | 227 |
| placebo | 0.7273 | 0.3070 | 0.5171 | 236 |
| placebo | 0.7629 | 0.3099 | 0.5364 | 241 |
| placebo | 0.7629 | 0.3099 | 0.5364 | 245 |
| placebo | 0.7829 | 0.3290 | 0.5560 | 246 |
| placebo | 0.8079 | 0.3433 | 0.5756 | 248 |
| placebo | 0.8482 | 0.3422 | 0.5952 | 249 |
| placebo | 0.8780 | 0.3516 | 0.6148 | 250 |
| placebo | 0.8780 | 0.3516 | 0.6148 | 252 |
| placebo | 0.9036 | 0.3660 | 0.6348 | 253 |
| placebo | 0.9321 | 0.3776 | 0.6548 | 255 |
| placebo | 0.9573 | 0.3932 | 0.6752 | 260 |
| placebo | 0.9573 | 0.3932 | 0.6752 | 261 |
| placebo | 0.9776 | 0.4144 | 0.6960 | 264 |
| placebo | 1.009 | 0.4253 | 0.7173 | 265 |
| placebo | 1.046 | 0.4309 | 0.7386 | 269 |
| placebo | 1.046 | 0.4309 | 0.7386 | 270 |
| placebo | 1.046 | 0.4309 | 0.7386 | 271 |
| placebo | 1.046 | 0.4309 | 0.7386 | 273 |
| placebo | 1.046 | 0.4309 | 0.7386 | 274 |
| placebo | 1.046 | 0.4309 | 0.7386 | 276 |
| placebo | 1.046 | 0.4309 | 0.7386 | 278 |
| placebo | 1.108 | 0.4835 | 0.7957 | 280 |
First 60 of 166 rows.
View data
| Rate ratio | upper | Term | lower |
|---|---|---|---|
| 0.3263 | 0.5989 | treat: rIFN-g | 0.1777 |
| 0.9699 | 0.9978 | age | 0.9428 |
Assumptions
- Non-overlapping intervals — Intervals of each subject do not overlap.
- Non-informative end of follow-up — 128 subjects followed for 37477 time units in total.
- Events per variable — 38.0 events per coefficient.
Rate ratios (Andersen–Gill)
| Term | β | Robust SE | Rate ratio | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| treat: rIFN-g | −1.120 | 0.3099 | 0.3263 | 0.1777 | 0.5989 | −3.614 | < .001 |
| age | −0.0305 | 0.0144 | 0.9699 | 0.9428 | 0.9978 | −2.114 | .034 |
Hazard (rate) ratios with robust standard errors clustered by subject.
Mean cumulative function
| treat | Time | Mean events per subject | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| placebo | 100 | 0.2466 | 0.0654 | 0.1184 | 0.3749 |
| placebo | 200 | 0.4079 | 0.0935 | 0.2247 | 0.5911 |
| placebo | 300 | 0.8930 | 0.1682 | 0.5633 | 1.223 |
| rIFN-g | 100 | 0.0317 | 0.0221 | −0.0115 | 0.0750 |
| rIFN-g | 200 | 0.1603 | 0.0564 | 0.0498 | 0.2708 |
| rIFN-g | 300 | 0.2795 | 0.0730 | 0.1364 | 0.4226 |
Lawless–Nadeau robust standard errors.
- Event: status = 1. Model: Andersen–Gill. Ties: efron.
RR = 0.33, 95% CI [0.18, 0.60], p < .001
- Events
- 76
- Events per subject
- 0.5938
- Robust Wald χ²
- 16.620
- p
- < .001
Effect size
- Rate ratio (treat: rIFN-g) 0.3263 95% CI [0.1777, 0.5989]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Non-overlapping intervals — Intervals of each subject do not overlap.
- Non-informative end of follow-up — 128 subjects followed for 37477 time units in total.
- Events per variable — 38.0 events per coefficient.
Rate ratios (Andersen–Gill)
| Term | β | Robust SE | Rate ratio | 95% CI low | 95% CI high | z | p |
|---|---|---|---|---|---|---|---|
| treat: rIFN-g | −1.120 | 0.3099 | 0.3263 | 0.1777 | 0.5989 | −3.614 | < .001 |
| age | −0.0305 | 0.0144 | 0.9699 | 0.9428 | 0.9978 | −2.114 | .034 |
Hazard (rate) ratios with robust standard errors clustered by subject.
Mean cumulative function
| treat | Time | Mean events per subject | SE | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| placebo | 100 | 0.2466 | 0.0654 | 0.1184 | 0.3749 |
| placebo | 200 | 0.4079 | 0.0935 | 0.2247 | 0.5911 |
| placebo | 300 | 0.8930 | 0.1682 | 0.5633 | 1.223 |
| rIFN-g | 100 | 0.0317 | 0.0221 | −0.0115 | 0.0750 |
| rIFN-g | 200 | 0.1603 | 0.0564 | 0.0498 | 0.2708 |
| rIFN-g | 300 | 0.2795 | 0.0730 | 0.1364 | 0.4226 |
Lawless–Nadeau robust standard errors.
- Event: status = 1. Model: Andersen–Gill. 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
- Cgd ag groups2_cgd · event: status · group: treat · id: id · predictors: treat, age · start: tstart · stop: tstop
- Cgd pwp tts2_cgd · event: status · id: id · predictors: treat, uses steroids · start: tstart · stop: tstop
- Bladder pwp gt breslows2_bladder · event: event · id: id · predictors: rx, number, size · start: start · stop: stop
- Bladder wlws2_bladder · event: event · id: id · predictors: rx, number, size · start: start · stop: stop
- Bladder mcf onlys2_bladder · event: event · group: rx · id: id · start: start · stop: stop
- Degenerate constants2_cgd · event: status · group: treat · id: id · predictors: treat, age · start: tstart · stop: tstop
- Degenerate huge cardinalitys2_cgd · event: status · group: treat · id: id · predictors: treat, age · start: tstart · stop: tstop
- Degenerate single levels2_cgd · event: status · group: treat · id: id · predictors: treat, age · start: tstart · stop: tstop
In the guides
Where it sits in the decision guides
- Time-to-event: Cox, survival models · Statistics Guide · D — Predict an outcome
- Interval censoring, recurrent events, delayed entry · Statistics Guide · F — Time-to-event analysis
What you need
- Subject idcategorical / numeric · 1 column
- Identifies the rows of one subject.
- Interval startnumeric · 1 column
- Start of the interval (exclusive) — zero or the time of the previous event.
- Interval stopnumeric · 1 column
- End of the interval — the time of an event or the end of follow-up.
- Eventboolean / numeric / categorical · 1 column
- Whether an event happened at the interval's stop time. Yes/no, 0/1 or 1/2 codes, or a category chosen below.
- Predictorsnumeric / categorical / boolean · 0–20 columns · 2–30 levels
- Optional — covariates for the regression model (leave empty for the mean cumulative function only).
- Groupscategorical / boolean · 0–1 column · 2–10 levels
- Optional — a mean cumulative function per group.
Choices you make
hypothesis
- Event leveldefault —
For a categorical event column, the level that marks the event (default the last level).
- Regression modeldefault ag
Andersen–Gill assumes events are alike; PWP lets the hazard differ for later events; WLW models the time to the k-th event marginally.
- Andersen–Gill (common baseline rate)(default) — All events share one baseline rate; the plainest view, assuming events are unrelated given the covariates.
- Prentice–Williams–Peterson, total time (baseline per event number) — Gives each event number its own baseline, on total time; pick it when risk changes with earlier events.
- Prentice–Williams–Peterson, gap time (time since the previous event) — Gives each event number its own baseline, on time since the last event; pick it when the clock resets after each one.
- Wei–Lin–Weissfeld marginal (each event from time 0) — Treats each event number as a separate outcome from time 0; pick it for a population-average view per event.
- Event numbers modeled separatelydefault 4
PWP pools events beyond this number into the last stratum; WLW models the first this many events.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
options
- Tied event timesdefault efron
How tied event times enter the partial likelihood. Efron is more accurate; Breslow matches older software.
- Efron (coxph's default)(default) — Approximates the likelihood for tied times more closely; the usual choice.
- Breslow — Uses a plainer approximation; matches SAS and Stata defaults, and is less accurate with many ties.
statistics
- Report the MCF at timesdefault
Times for the mean cumulative function table (default 25%, 50% and 75% of the longest follow-up).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Non-overlapping intervals
A subject's intervals must not overlap.
Non-informative end of follow-up
The end of follow-up must be unrelated to the event process (e.g. not caused by a terminal event).
Events per variable
At least about 10 events per estimated coefficient.
What it reports
- Tests: Model robust Wald test
- Tests: First predictor's rate ratio
- n_subjects
- How many independent units the analysis used; it sets precision and power.
- n_rows
- 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.
- mean_events
- In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.
- max_events_subject
- In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.
- model_label
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- n_coef
- How many coefficients the model estimated, counting the intercept.
- lr_chisq
- Compares nested models by how much the log-likelihood improves when parameters are added.
- lr_df
- Compares nested models by how much the log-likelihood improves when parameters are added.
- lr_p
- Compares nested models by how much the log-likelihood improves when parameters are added.
- wald_chisq
- A sum of squared, scaled differences between observed and expected counts or estimates.
- wald_p
- Tests a parameter by dividing its estimate by its standard error; quick, but unreliable near boundaries or with separation.
- coef_1_label
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- 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.
- event_label
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
Per group, level or term: mcf[<curve>@<time>], mcf_se[<curve>@<time>], coef[<term>], se[<term>], naive_se[<term>], hr[<term>], hr_low[<term>], hr_high[<term>], z[<term>], p[<term>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-7). Python uses pandas, numpy, scipy, codesplash; R uses survival, nanoparquet, codesplashr.
Default traps between the two languages
- R fits coxph(…, cluster = id) (with strata for PWP/WLW; WLW data built by codesplashr::cs_surv_wlw) and takes the MCF from survfit(Surv(start, stop, event) ~ 1, id = id) (cumhaz, std.chaz — the infinitesimal-jackknife SE equals Lawless–Nadeau's); Python uses codesplash.stats.survival_adv (cox_cp with the same robust variance, mcf). Agreement ≈ 1e-10.
The exact script CodeSplash ran for example “Cgd ag group” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Recurrent events (mean cumulative function, Andersen–Gill, PWP, WLW)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.recurrent 1.0.1 · spec 47c780e24b140a3e
# Dataset: s2_cgd (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 # report times
from codesplash.stats import survival_adv as sa # coxph for (start, stop] data with robust SEs, MCF, PWP/WLW data
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s2_cgd.parquet", columns=["id", "tstart", "tstop", "status", "treat", "age"])
n_input = len(df)
df["id"] = pd.Categorical(df["id"], categories=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114", "115", "116", "117", "118", "119", "121", "122", "123", "125", "131", "132", "133", "134", "135"]) # stored level order
df["treat"] = pd.Categorical(df["treat"], categories=["placebo", "rIFN-g"]) # stored level order
df = df.dropna(subset=["id", "tstart", "tstop", "status", "treat", "age"]) # listwise deletion over the analysis columns
df["id"] = df["id"].cat.remove_unused_categories()
df["treat"] = df["treat"].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, ["id", "tstart", "tstop", "status", "treat", "age"]) # infinite values stop the run (registry/errors.yaml)
# %% Counting-process data: one row per (start, stop] interval
scol = "tstart"
tcol = "tstop"
ecol = "status"
t0 = df[scol].to_numpy(dtype=float)
t1 = df[tcol].to_numpy(dtype=float)
bad_rows = int(np.sum(t1 <= t0))
if bad_rows:
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement=f"later than {scol} on every row", count=bad_rows)
codes = set(np.unique(df[ecol].to_numpy(dtype=float)).tolist())
if codes <= {0.0, 1.0}:
event_code = 1.0 # 0 = censored, 1 = event
elif codes <= {1.0, 2.0}:
event_code = 2.0 # 1 = censored, 2 = event (survival::Surv convention)
else:
raise ValueError(f"{ecol} must be coded 0/1 or 1/2 (the larger code is the event), or be a yes/no or categorical column")
ev = df[ecol].to_numpy(dtype=float) == event_code
event_label = f"{ecol} = {event_code:g}"
if not ev.any():
cs.cs_error("CS_E_NO_EVENTS", event=event_label)
# %% Subjects and events
idcol = "id"
ids = df[idcol].astype(str).to_numpy()
subjects = np.unique(ids)
n_subjects = len(subjects)
per_subject = pd.Series(ev.astype(int)).groupby(ids).sum()
order = np.lexsort((t0, ids))
same = ids[order][1:] == ids[order][:-1]
n_overlap = int(np.sum(same & (t0[order][1:] < t1[order][:-1])))
conf = 0.95
ties = "efron"
model = "ag"
K = int(4)
model_label = {"ag": "Andersen–Gill", "pwp_tt": "PWP total-time", "pwp_gt": "PWP gap-time", "wlw": "Wei–Lin–Weissfeld"}[model]
# %% Mean cumulative function (Lawless–Nadeau robust SE, normal interval)
times = [100, 200, 300, ] or sv.default_times(t1)
q = stats.norm.ppf(1 - (1 - conf) / 2)
g = "treat"
curves = [str(x) for x in df[g].cat.categories]
gv = df[g].astype(str).to_numpy()
values = {}
mcf_rows = []
chart = {"time": [], "surv": [], "low": [], "high": [], "strata": []}
for cname in curves:
m = gv == cname
res = sa.mcf(t0[m], t1[m], ev[m], ids[m], conf=conf)
for x in times:
est = sa.step_at(res["time"], res["mcf"], x, 0.0)
se_x = sa.step_at(res["time"], res["se"], x, 0.0)
values[f"mcf[{cname}@{sv.key_num(x)}]"] = est
values[f"mcf_se[{cname}@{sv.key_num(x)}]"] = se_x
mcf_rows.append({"curve": cname, "time": float(x), "mcf": est, "se": se_x, "low": est - q * se_x, "high": est + q * se_x})
chart["time"] += [0.0] + res["time"].tolist()
chart["surv"] += [0.0] + res["mcf"].tolist()
chart["low"] += [0.0] + res["lower"].tolist()
chart["high"] += [0.0] + res["upper"].tolist()
chart["strata"] += [cname] * (len(res["time"]) + 1)
values.update({
"n_subjects": float(n_subjects), "n_rows": float(len(t1)), "events": float(ev.sum()), "mean_events": float(ev.sum()) / n_subjects,
"max_events_subject": float(per_subject.max()), "model_label": model_label, "event_label": event_label,
})
# %% Regression model (robust SEs clustered by subject)
preds = ["treat", "age"]
coef_rows = []
# %% Design matrix for `preds` (treatment contrasts against the first stored level)
cols, labels, terms = [], [], []
for pname in preds:
s = df[pname]
if isinstance(s.dtype, pd.CategoricalDtype):
lv = [str(x) for x in s.cat.categories]
if len(lv) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=pname, min=2, k=len(lv)) # a factor needs two levels with data
idx = []
for level in lv[1:]:
idx.append(len(cols))
cols.append((s.astype(str) == level).to_numpy(dtype=float))
labels.append(f"{pname}: {level}")
terms.append(idx)
else:
terms.append([len(cols)])
cols.append(s.to_numpy(dtype=float))
labels.append(pname)
X = np.column_stack(cols) if cols else np.zeros((len(df), 0))
if preds:
if model == "ag":
fit = sa.cox_cp(t0, t1, ev, X, ties=ties, cluster=ids)
elif model == "pwp_tt":
enum = np.minimum(sa.episode_numbers(ids, t0, ev), K)
fit = sa.cox_cp(t0, t1, ev, X, strata=enum, ties=ties, cluster=ids)
elif model == "pwp_gt":
enum = np.minimum(sa.episode_numbers(ids, t0, ev), K)
fit = sa.cox_cp(np.zeros(len(t1)), t1 - t0, ev, X, strata=enum, ties=ties, cluster=ids)
else: # WLW: the k-th event time from time 0 for k = 1..K
K_eff = int(min(K, per_subject.max()))
w = sa.wlw_data(ids, t0, t1, ev, K_eff)
fit = sa.cox_cp(np.zeros(len(w["time"])), w["time"], w["status"] == 1, X[w["row"]], strata=w["k"], ties=ties,
cluster=ids[w["row"]])
beta = fit["coef"]
naive_se = np.sqrt(np.diag(fit["cov"]))
V = fit["rcov"]
se = np.sqrt(np.diag(V))
z = beta / se
pv = 2 * stats.norm.sf(np.abs(z))
hr, hr_lo, hr_hi = np.exp(beta), np.exp(beta - q * se), np.exp(beta + q * se)
k = len(beta)
wald = float(beta @ np.linalg.solve(V, beta))
values.update({
"n_coef": float(k), "lr_chisq": fit["lr"], "lr_df": float(k), "lr_p": float(stats.chi2.sf(fit["lr"], k)),
"wald_chisq": wald, "wald_p": float(stats.chi2.sf(wald, k)), "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]),
})
for i, lab in enumerate(labels):
for key, val in (("coef", beta[i]), ("se", se[i]), ("naive_se", naive_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)
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])})
else:
k = 0
for key in ("n_coef", "lr_chisq", "lr_df", "lr_p", "wald_chisq", "wald_p", "coef_1_label", "hr_1", "hr_1_low", "hr_1_high", "p_1"):
values[key] = None
# %% Assumptions
assumptions = [
{"key": "intervals", "label": "Non-overlapping intervals", "status": "fail" if n_overlap else "pass",
"detail": f"{n_overlap} intervals overlap the subject's previous interval." if n_overlap else "Intervals of each subject do not overlap."},
{"key": "censoring", "label": "Non-informative end of follow-up", "status": "info",
"detail": f"{n_subjects} subjects followed for {float(np.sum(t1 - t0)):.6g} time units in total."},
]
if k:
epv = float(ev.sum()) / k
assumptions.append({"key": "events_per_variable", "label": "Events per variable", "status": "warn" if epv < 10 else "pass",
"detail": f"{epv:.1f} events per coefficient."})
# %% Result
pct = f"{conf:.0%}"
tables = [{"key": "mcf", "title": "Mean cumulative function", "columns": [
{"key": "curve", "label": g or "Curve", "type": "string"}, {"key": "time", "label": "Time", "type": "number"},
{"key": "mcf", "label": "Mean events per subject", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"},
], "rows": mcf_rows, "note": "Lawless–Nadeau robust standard errors."}]
charts = [cs.chart("mcf", "mcf-plot", "Mean cumulative function" + (f" by {g}" if g else ""), {
"time": cs.col(tcol, chart["time"], "numeric"), "mcf": cs.col("Mean events per subject", chart["surv"], "numeric"),
"low": cs.col("lower", chart["low"], "numeric"), "high": cs.col("upper", chart["high"], "numeric"),
"group": cs.col(g or "Curve", chart["strata"], "categorical", levels=curves),
})]
if coef_rows:
tables.insert(0, {"key": "coefficients", "title": f"Rate ratios ({model_label})", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "coef", "label": "β", "type": "number"},
{"key": "se", "label": "Robust SE", "type": "number"}, {"key": "hr", "label": "Rate ratio", "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, "note": "Hazard (rate) ratios with robust standard errors clustered by subject."})
charts.append(cs.chart("hr", "forest", f"Rate ratios ({model_label})", {
"label": cs.col("Term", labels, "categorical", levels=labels), "estimate": cs.col("Rate ratio", hr, "numeric"),
"low": cs.col("lower", hr_lo, "numeric"), "high": cs.col("upper", hr_hi, "numeric"),
}, controls={"reference": 1, "log": True}))
cs.publish({
"method": "survival.recurrent",
"methodVersion": "1.0.1",
"title": "Recurrent events" + (f" — {model_label} model" if coef_rows else ""),
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n_subjects),
"summary": f"{int(ev.sum())} events in {n_subjects} subjects ({float(ev.sum()) / n_subjects:.2f} per subject)"
+ (f"; {model_label} robust Wald χ²({k}) = {values['wald_chisq']:.2f}, {cs.fmt_p(values['wald_p'])}." if coef_rows else "."),
"apa": (f"RR = {cs.fmt_num(hr[0])}, {pct} CI [{cs.fmt_num(hr_lo[0])}, {cs.fmt_num(hr_hi[0])}], {cs.fmt_p(pv[0])}" if coef_rows
else f"{int(ev.sum())} events in {n_subjects} subjects"),
"statistics": [{"key": "events", "label": "Events", "value": float(ev.sum()), "format": "integer"},
{"key": "mean_events", "label": "Events per subject", "value": values["mean_events"]}]
+ ([{"key": "wald_chisq", "label": "Robust Wald χ²", "value": values["wald_chisq"]},
{"key": "wald_p", "label": "p", "value": values["wald_p"], "format": "p"}] if coef_rows else []),
"tables": tables,
"effectSizes": ([{"key": "hr_1", "label": f"Rate ratio ({labels[0]})", "value": float(hr[0]), "ciLow": float(hr_lo[0]),
"ciHigh": float(hr_hi[0]), "ciLevel": conf, "method": "Wald interval on log(RR), robust SE"}] if coef_rows else []),
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {event_label}. Model: {model_label}" + (f" (event numbers above {K} pooled)" if model in ("pwp_tt", "pwp_gt") else "")
+ (f" (first {min(K, int(per_subject.max()))} events)" if model == "wlw" else "") + f". Ties: {ties}."],
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Cgd ag group” · R version 4.5.1 (2025-06-13)
# Recurrent events (mean cumulative function, Andersen–Gill, PWP, WLW)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.recurrent 1.0.1 · spec 47c780e24b140a3e
# Dataset: s2_cgd (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/s2_cgd.parquet", col_select = c("id", "tstart", "tstop", "status", "treat", "age")))
n_input <- nrow(df)
df[["id"]] <- factor(df[["id"]], levels = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "101", "102", "103", "104", "105", "106", "107", "108", "109", "110", "111", "112", "113", "114", "115", "116", "117", "118", "119", "121", "122", "123", "125", "131", "132", "133", "134", "135")) # stored level order
df[["treat"]] <- factor(df[["treat"]], levels = c("placebo", "rIFN-g")) # stored level order
df <- df[stats::complete.cases(df[c("id", "tstart", "tstop", "status", "treat", "age")]), , 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("id", "tstart", "tstop", "status", "treat", "age")) # infinite values stop the run (registry/errors.yaml)
# %% Counting-process data: one row per (start, stop] interval
scol <- "tstart"
tcol <- "tstop"
ecol <- "status"
t0 <- as.numeric(df[[scol]])
t1 <- as.numeric(df[[tcol]])
bad_rows <- sum(t1 <= t0)
if (bad_rows > 0) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = sprintf("later than %s on every row", scol), count = bad_rows)
codes <- sort(unique(df[[ecol]]))
if (all(codes %in% c(0, 1))) {
event_code <- 1 # 0 = censored, 1 = event
} else if (all(codes %in% c(1, 2))) {
event_code <- 2 # 1 = censored, 2 = event (survival::Surv convention)
} else {
stop(sprintf("%s must be coded 0/1 or 1/2 (the larger code is the event), or be a yes/no or categorical column", ecol))
}
ev <- df[[ecol]] == event_code
event_label <- sprintf("%s = %s", ecol, format(event_code))
if (!any(ev)) cs_error("CS_E_NO_EVENTS", event = event_label)
# %% Subjects and events
idcol <- "id"
ids <- as.character(df[[idcol]])
n_subjects <- length(unique(ids))
per_subject <- tapply(as.integer(ev), ids, sum)
o <- order(ids, t0, method = "radix")
same <- ids[o][-1] == ids[o][-length(o)]
n_overlap <- sum(same & (t0[o][-1] < t1[o][-length(o)]))
conf <- 0.95
ties <- "efron"
model <- "ag"
K <- as.integer(4)
model_label <- switch(model, ag = "Andersen–Gill", pwp_tt = "PWP total-time", pwp_gt = "PWP gap-time", wlw = "Wei–Lin–Weissfeld")
q <- stats::qnorm(1 - (1 - conf) / 2)
# %% Mean cumulative function: survfit's cumulative hazard with id (robust = Lawless–Nadeau SE)
times <- c(100, 200, 300)
if (length(times) == 0) times <- cs_default_times(t1)
g <- "treat"
curves <- levels(df[[g]])
gv <- as.character(df[[g]])
values <- list()
mcf_rows <- list()
chart <- list(time = numeric(0), mcf = numeric(0), low = numeric(0), high = numeric(0), strata = character(0))
for (cname in curves) {
m <- gv == cname
sf <- survfit(Surv(t0[m], t1[m], ev[m]) ~ 1, id = ids[m], robust = TRUE) # robust even when every id has one row
est <- cs_step_at(sf$time, sf$cumhaz, times, start = 0)
se_x <- cs_step_at(sf$time, sf$std.chaz, times, start = 0)
for (i in seq_along(times)) {
values[[sprintf("mcf[%s@%s]", cname, cs_key_num(times[i]))]] <- est[i]
values[[sprintf("mcf_se[%s@%s]", cname, cs_key_num(times[i]))]] <- se_x[i]
mcf_rows[[length(mcf_rows) + 1]] <- list(curve = cname, time = times[i], mcf = est[i], se = se_x[i],
low = est[i] - q * se_x[i], high = est[i] + q * se_x[i])
}
chart$time <- c(chart$time, 0, sf$time)
chart$mcf <- c(chart$mcf, 0, sf$cumhaz)
chart$low <- c(chart$low, 0, sf$cumhaz - q * sf$std.chaz)
chart$high <- c(chart$high, 0, sf$cumhaz + q * sf$std.chaz)
chart$strata <- c(chart$strata, rep(cname, length(sf$time) + 1))
}
values <- c(values, list(n_subjects = n_subjects, n_rows = length(t1), events = sum(ev), mean_events = sum(ev) / n_subjects,
max_events_subject = max(per_subject), model_label = model_label, event_label = event_label))
# %% Regression model (robust SEs clustered by subject)
preds <- c("treat", "age")
coef_rows <- list()
k <- 0L
dd <- data.frame(.start = t0, .stop = t1, .e = ev, .id = ids)
# %% Predictors `preds` (treatment contrasts against the first stored level) into `dd`
labels <- character(0)
for (pname in preds) {
x <- df[[pname]]
if (is.factor(x)) {
if (nlevels(x) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = pname, min = 2, k = nlevels(x)) # a factor needs two levels with data
labels <- c(labels, paste0(pname, ": ", levels(x)[-1]))
} else {
labels <- c(labels, pname)
}
dd[[pname]] <- x
}
rhs <- if (length(preds)) paste(sprintf("`%s`", gsub("`", "\\\\`", preds)), collapse = " + ") else "1"
if (length(preds)) {
ctl <- coxph.control(eps = 1e-12, toler.chol = 1e-15, iter.max = 60)
if (model == "ag") {
fit <- coxph(stats::as.formula(paste("Surv(.start, .stop, .e) ~", rhs)), data = dd, cluster = .id, ties = ties, control = ctl)
} else if (model == "pwp_tt") {
dd$.enum <- pmin(cs_surv_episode(ids, t0, ev), K)
fit <- coxph(stats::as.formula(paste("Surv(.start, .stop, .e) ~", rhs, "+ strata(.enum)")), data = dd, cluster = .id, ties = ties, control = ctl)
} else if (model == "pwp_gt") {
dd$.enum <- pmin(cs_surv_episode(ids, t0, ev), K)
dd$.gap <- t1 - t0
fit <- coxph(stats::as.formula(paste("Surv(.gap, .e) ~", rhs, "+ strata(.enum)")), data = dd, cluster = .id, ties = ties, control = ctl)
} else {
w <- cs_surv_wlw(ids, t0, t1, ev, min(K, max(per_subject)))
dw <- dd[w$row, , drop = FALSE]
dw$.time <- w$time
dw$.status <- w$status
dw$.k <- w$k
fit <- coxph(stats::as.formula(paste("Surv(.time, .status) ~", rhs, "+ strata(.k)")), data = dw, cluster = .id, ties = ties, control = ctl)
}
beta <- unname(coef(fit))
if (anyNA(beta)) stop("Some coefficients could not be estimated (collinear predictors).")
V <- unname(fit$var)
naive_se <- sqrt(diag(unname(fit$naive.var)))
se <- sqrt(diag(V))
z <- beta / se
pv <- 2 * stats::pnorm(-abs(z))
hr <- exp(beta)
hr_lo <- exp(beta - q * se)
hr_hi <- exp(beta + q * se)
k <- length(beta)
lr <- 2 * diff(fit$loglik)
wald <- drop(beta %*% solve(V, beta))
values <- c(values, list(n_coef = k, lr_chisq = lr, lr_df = k, lr_p = stats::pchisq(lr, k, lower.tail = FALSE),
wald_chisq = wald, wald_p = stats::pchisq(wald, k, lower.tail = FALSE), 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]))
for (i in seq_along(labels)) {
lab <- labels[i]
vals <- list(coef = beta[i], se = se[i], naive_se = naive_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]]
coef_rows[[i]] <- c(list(term = lab), vals[c("coef", "se", "hr", "hr_low", "hr_high", "z", "p")])
}
} else {
for (key in c("n_coef", "lr_chisq", "lr_df", "lr_p", "wald_chisq", "wald_p", "coef_1_label", "hr_1", "hr_1_low", "hr_1_high", "p_1")) {
values[key] <- list(NULL)
}
}
# %% Assumptions
assumptions <- list(
list(key = "intervals", label = "Non-overlapping intervals", status = if (n_overlap > 0) "fail" else "pass",
detail = if (n_overlap > 0) sprintf("%d intervals overlap the subject's previous interval.", n_overlap) else "Intervals of each subject do not overlap."),
list(key = "censoring", label = "Non-informative end of follow-up", status = "info",
detail = sprintf("%d subjects followed for %s time units in total.", n_subjects, format(sum(t1 - t0), digits = 6)))
)
if (k > 0) {
epv <- sum(ev) / k
assumptions[[3]] <- list(key = "events_per_variable", label = "Events per variable", status = if (epv < 10) "warn" else "pass",
detail = sprintf("%.1f events per coefficient.", epv))
}
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
tables <- list(list(key = "mcf", title = "Mean cumulative function", columns = list(
list(key = "curve", label = if (is.null(g)) "Curve" else g, type = "string"), list(key = "time", label = "Time", type = "number"),
list(key = "mcf", label = "Mean events per subject", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "low", label = paste(pct, "CI low"), type = "number"), list(key = "high", label = paste(pct, "CI high"), type = "number")
), rows = mcf_rows, note = "Lawless–Nadeau robust standard errors."))
charts <- list(cs_chart("mcf", "mcf-plot", paste0("Mean cumulative function", if (!is.null(g)) paste(" by", g) else ""), list(
time = cs_col(tcol, chart$time, "numeric"), mcf = cs_col("Mean events per subject", chart$mcf, "numeric"),
low = cs_col("lower", chart$low, "numeric"), high = cs_col("upper", chart$high, "numeric"),
group = cs_col(if (is.null(g)) "Curve" else g, chart$strata, "categorical", levels = curves)
)))
if (length(coef_rows)) {
tables <- c(list(list(key = "coefficients", title = sprintf("Rate ratios (%s)", model_label), columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "coef", label = "β", type = "number"),
list(key = "se", label = "Robust SE", type = "number"), list(key = "hr", label = "Rate ratio", 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, note = "Hazard (rate) ratios with robust standard errors clustered by subject.")), tables)
charts[[2]] <- cs_chart("hr", "forest", sprintf("Rate ratios (%s)", model_label), list(
label = cs_col("Term", labels, "categorical", levels = labels), estimate = cs_col("Rate ratio", hr, "numeric"),
low = cs_col("lower", hr_lo, "numeric"), high = cs_col("upper", hr_hi, "numeric")
), controls = list(reference = 1, log = TRUE))
}
cs_publish(list(
method = "survival.recurrent",
methodVersion = "1.0.1",
title = paste0("Recurrent events", if (length(coef_rows)) paste(" —", model_label, "model") else ""),
engine = cs_engine_info("survival", "codesplashr"),
n = n_subjects,
summary = paste0(sprintf("%d events in %d subjects (%.2f per subject)", sum(ev), n_subjects, sum(ev) / n_subjects),
if (length(coef_rows)) sprintf("; %s robust Wald χ²(%d) = %.2f, %s.", model_label, k, values$wald_chisq, cs_fmt_p(values$wald_p)) else "."),
apa = if (length(coef_rows)) sprintf("RR = %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]))
else sprintf("%d events in %d subjects", sum(ev), n_subjects),
statistics = c(list(list(key = "events", label = "Events", value = sum(ev), format = "integer"),
list(key = "mean_events", label = "Events per subject", value = values$mean_events)),
if (length(coef_rows)) list(list(key = "wald_chisq", label = "Robust Wald χ²", value = values$wald_chisq),
list(key = "wald_p", label = "p", value = values$wald_p, format = "p")) else list()),
tables = tables,
effectSizes = if (length(coef_rows)) list(list(key = "hr_1", label = sprintf("Rate ratio (%s)", labels[1]), value = hr[1], ciLow = hr_lo[1],
ciHigh = hr_hi[1], ciLevel = conf, method = "Wald interval on log(RR), robust SE")) else list(),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(sprintf("Event: %s. Model: %s", event_label, model_label),
if (model %in% c("pwp_tt", "pwp_gt")) sprintf(" (event numbers above %d pooled)", K) else "",
if (model == "wlw") sprintf(" (first %d events)", min(K, max(per_subject))) else "", sprintf(". Ties: %s.", ties))),
charts = charts,
values = values
))
Sources
- Andersen, P. K., & Gill, R. D. (1982). Cox's regression model for counting processes. Annals of Statistics, 10, 1100–1120.
- Prentice, R. L., Williams, B. J., & Peterson, A. V. (1981). On the regression analysis of multivariate failure time data. Biometrika, 68, 373–379.
- Wei, L. J., Lin, D. Y., & Weissfeld, L. (1989). Regression analysis of multivariate incomplete failure time data by modeling marginal distributions. JASA, 84, 1065–1073.
- Lawless, J. F., & Nadeau, C. (1995). Some simple robust methods for the analysis of recurrent events. Technometrics, 37, 158–168.
- Amorim, L. D., & Cai, J. (2015). Modelling recurrent events: a tutorial for analysis in epidemiology. International Journal of Epidemiology, 44, 324–333.
From the CodeSplash method registry · survival.recurrent v1.0.1.