Skip to content

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.

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

A real result

Example “Cgd ag group”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Recurrent events — Andersen–Gill modelRecorded · Python and R agreeRecorded 2026-11-17 · 46 values compared
R

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

Mean cumulative function by treatFor repeated events (readmissions, failures, purchases), how many events per subject accumulate over time?
View data
treatupperlowerMean events per subjecttstop
placebo0000
placebo0.0453−0.01450.01544
placebo0.0728−0.01120.03086
placebo0.0972−0.00490.04628
placebo0.12000.00310.061511
placebo0.14170.01210.076914
placebo0.16270.02190.092318
placebo0.18310.03230.107719
placebo0.21360.03250.123122
placebo0.23260.04430.138523
placebo0.26030.04740.153826
placebo0.27850.05990.169252
placebo0.29660.07270.184657
placebo0.32210.07790.200065
placebo0.33970.09110.215467
placebo0.35700.10450.230891
placebo0.37490.11840.246699
placebo0.37490.11840.2466102
placebo0.39310.13250.2628104
placebo0.41100.14680.2789120
placebo0.46000.16230.3112121
placebo0.47740.17710.3273146
placebo0.50690.18000.3434152
placebo0.52970.18940.3595159
placebo0.54670.20460.3757168
placebo0.57440.20930.3918169
placebo0.59110.22470.4079175
placebo0.59110.22470.4079192
placebo0.59110.22470.4079195
placebo0.59110.22470.4079198
placebo0.59110.22470.4079200
placebo0.62040.23000.4252203
placebo0.63920.24680.4430206
placebo0.63920.24680.4430207
placebo0.65830.26410.4612211
placebo0.68810.27070.4794213
placebo0.70730.28850.4979226
placebo0.70730.28850.4979227
placebo0.72730.30700.5171236
placebo0.76290.30990.5364241
placebo0.76290.30990.5364245
placebo0.78290.32900.5560246
placebo0.80790.34330.5756248
placebo0.84820.34220.5952249
placebo0.87800.35160.6148250
placebo0.87800.35160.6148252
placebo0.90360.36600.6348253
placebo0.93210.37760.6548255
placebo0.95730.39320.6752260
placebo0.95730.39320.6752261
placebo0.97760.41440.6960264
placebo1.0090.42530.7173265
placebo1.0460.43090.7386269
placebo1.0460.43090.7386270
placebo1.0460.43090.7386271
placebo1.0460.43090.7386273
placebo1.0460.43090.7386274
placebo1.0460.43090.7386276
placebo1.0460.43090.7386278
placebo1.1080.48350.7957280

First 60 of 166 rows.

Rate ratios (Andersen–Gill)How large are several estimates, how precise, and which exclude the null?
View data
Rate ratioupperTermlower
0.32630.5989treat: rIFN-g0.1777
0.96990.9978age0.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 SERate ratio95% CI low95% CI highzp
treat: rIFN-g−1.1200.30990.32630.17770.5989−3.614< .001
age−0.03050.01440.96990.94280.9978−2.114.034

Hazard (rate) ratios with robust standard errors clustered by subject.

Mean cumulative function

treatTimeMean events per subjectSE95% CI low95% CI high
placebo1000.24660.06540.11840.3749
placebo2000.40790.09350.22470.5911
placebo3000.89300.16820.56331.223
rIFN-g1000.03170.0221−0.01150.0750
rIFN-g2000.16030.05640.04980.2708
rIFN-g3000.27950.07300.13640.4226

Lawless–Nadeau robust standard errors.

  • Event: status = 1. Model: Andersen–Gill. Ties: efron.
Python

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 SERate ratio95% CI low95% CI highzp
treat: rIFN-g−1.1200.30990.32630.17770.5989−3.614< .001
age−0.03050.01440.96990.94280.9978−2.114.034

Hazard (rate) ratios with robust standard errors clustered by subject.

Mean cumulative function

treatTimeMean events per subjectSE95% CI low95% CI high
placebo1000.24660.06540.11840.3749
placebo2000.40790.09350.22470.5911
placebo3000.89300.16820.56331.223
rIFN-g1000.03170.0221−0.01150.0750
rIFN-g2000.16030.05640.04980.2708
rIFN-g3000.27950.07300.13640.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.
Python

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

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.