Skip to content

FTime to event · survival.cox_tv

Cox model with time-varying covariates (start–stop data)

How is the hazard associated with covariates whose values change during follow-up, or whose effect changes over time?

Fits a Cox model to counting-process data — one row per interval (start, stop] in which the covariates are constant — so covariates can change during follow-up (treatment switches, updated measurements) and subjects can enter late (delayed entry). Optional time-varying effects add x × log(t) or x × t terms (coxph's tt()). With a subject id, standard errors are robust (sandwich, clustered by subject). Reports hazard ratios with confidence intervals and the likelihood-ratio, Wald and score tests.

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

A real result

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

Cox model with time-varying covariatesRecorded · Python and R agreeRecorded 2026-11-17 · 47 values compared · largest relative difference 1.6e-11
R

HR = 1.03, 95% CI [1.00, 1.06], p = .033

Likelihood-ratio χ²
10.719
df
3
p
.013
Events
75

Effect size

  • Hazard ratio (age) 1.031 95% CI [1.002, 1.060]

Plots

Hazard ratiosHow large are several estimates, how precise, and which exclude the null?
View data
Hazard ratioupperTermlower
1.0311.060age1.002
0.46150.8868surgery: true0.2402
1.0161.863transplant: true0.5542

Assumptions

  • Events per variable — 25.0 events per coefficient.
  • Non-overlapping intervals — Intervals of each subject do not overlap.
  • Non-informative censoring and entry — 97 of 172 intervals end without the event; 0 subjects enter after time 0 (delayed entry is handled by the risk sets).

Hazard ratios

TermβSEHR95% CI low95% CI highzp
age0.03050.01431.0311.0021.0602.131.033
surgery: true−0.77330.33320.46150.24020.8868−2.321.020
transplant: true0.01610.30931.0160.55421.8630.0520.958

Standard errors: robust (clustered by subject).

Overall tests

Testχ²dfp
Likelihood ratio10.7193.013
Wald (robust)10.8043.013
Score10.0023.019
  • Event: event = 1. Ties: efron.
Python

HR = 1.03, 95% CI [1.00, 1.06], p = .033

Likelihood-ratio χ²
10.719
df
3
p
.013
Events
75

Effect size

  • Hazard ratio (age) 1.031 95% CI [1.002, 1.060]

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

Assumptions

  • Events per variable — 25.0 events per coefficient.
  • Non-overlapping intervals — Intervals of each subject do not overlap.
  • Non-informative censoring and entry — 97 of 172 intervals end without the event; 0 subjects enter after time 0 (delayed entry is handled by the risk sets).

Hazard ratios

TermβSEHR95% CI low95% CI highzp
age0.03050.01431.0311.0021.0602.131.033
surgery: true−0.77330.33320.46150.24020.8868−2.321.020
transplant: true0.01610.30931.0160.55421.8630.0520.958

Standard errors: robust (clustered by subject).

Overall tests

Testχ²dfp
Likelihood ratio10.7193.013
Wald (robust)10.8043.013
Score10.0023.019
  • Event: event = 1. 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

  • Heart transplants2_heart · event: event · id: id · predictors: age, surgery, transplant · start: start · stop: stop
  • Heart tt breslow naives2_heart · event: event · predictors: transplant, prior surgery · start: start · stop: stop · time_effects: age
  • Heart tt identity ids2_heart · event: event · id: id · predictors: age, transplant · start: start · stop: stop · time_effects: transplant
  • Cgd stratas2_cgd · event: status · id: id · predictors: treat, age, uses steroids · start: tstart · stop: tstop · strata: inherit
  • Degenerate single levels2_heart · event: event · id: id · predictors: age, surgery, transplant · start: start · stop: stop
  • Degenerate tiess2_heart · event: event · id: id · predictors: age, surgery, transplant · start: start · stop: stop

In the guides

Where it sits in the decision guides

  • Time-to-event: Cox, survival models · Statistics Guide · D — Predict an outcome
  • Model predictors: Cox PH · Statistics Guide · F — Time-to-event analysis
  • Time-varying covariates: extended Cox · Statistics Guide · F — Time-to-event analysis
  • Interval censoring, recurrent events, delayed entry · Statistics Guide · F — Time-to-event analysis

What you need

Interval startnumeric · 1 column
Start of the interval (exclusive). Zero for the first interval of a subject; later for delayed entry.
Interval stopnumeric · 1 column
End of the interval (inclusive) — the event or censoring time if the interval is the subject's last.
Eventboolean / numeric / categorical · 1 column
Whether the event happened at the interval's stop time. Yes/no, 0/1 or 1/2 codes, or a category chosen below.
Predictorsnumeric / categorical / boolean · 1–20 columns · 2–30 levels
Covariates, with their value during each interval. Categorical predictors use treatment contrasts against their first stored level.
Time-varying effectsnumeric / boolean · 0–5 columns
Optional — predictors whose effect may change over time; each adds a term x × g(t) evaluated at every event time (coxph's tt()). They are also included as main effects.
Subject idcategorical / numeric · 0–1 column
Optional — identifies the rows of one subject; gives robust standard errors clustered by subject and counts subjects.
Stratacategorical / boolean · 0–1 column · 2–50 levels
Optional — a separate baseline hazard per stratum.

Choices you make

hypothesis

Event leveldefault —

For a categorical event column, the level that marks the event (default the last level).

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

options

Tied event timesdefault efron

How tied event times enter the partial likelihood. Efron is more accurate; Breslow matches older software.

  • Efron (recommended; coxph's default)(default) — Approximates the likelihood for tied times more closely; the usual choice.
  • Breslow (SAS/Stata's default) — Uses a plainer approximation; matches SAS and Stata defaults, and is less accurate with many ties.
Time function g(t)default log

How the effect of the time-varying-effect predictors changes with time.

  • log(t) — the usual choice(default) — The effect changes with log time, quickly at first and then slowly; the usual choice.
  • t — The effect changes in a straight line with time; pick it when the change holds steady.
Robust standard errorsdefault on

With a subject id, use the sandwich variance clustered by subject (coxph's cluster()); otherwise model-based.

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.

  • Events per variable

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

  • Non-overlapping intervals

    A subject's intervals must not overlap; covariate values must be known at the start of each interval (no look-ahead).

  • Non-informative censoring and entry

    Censoring and late entry must be unrelated to prognosis given the covariates.

What it reports

  • Tests: Model likelihood-ratio test
  • Tests: First predictor's hazard ratio
n_rows
How many independent units the analysis used; it sets precision and power.
n_subjects
How many independent units the analysis used; it sets precision and power.
n_delayed
How many independent units the analysis used; it sets precision and power.
events
In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.
n_coef
How many coefficients the model estimated, counting the intercept.
n_tt
How many independent units the analysis used; it sets precision and power.
loglik
The logarithm of the likelihood; higher (less negative) means the model fits the data better.
loglik0
How well a model with no predictors fits. The likelihood-ratio test compares the fitted model with it.
lr_chisq
Compares nested models by how much the log-likelihood improves when parameters are added.
lr_df
Compares nested models by how much the log-likelihood improves when parameters are added.
lr_p
Compares nested models by how much the log-likelihood improves when parameters are added.
wald_chisq
A sum of squared, scaled differences between observed and expected counts or estimates.
wald_p
Tests a parameter by dividing its estimate by its standard error; quick, but unreliable near boundaries or with separation.
score_chisq
A sum of squared, scaled differences between observed and expected counts or estimates.
score_p
How surprising your data would be if the null hypothesis were true, as a probability.
coef_1_label
Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
hr_1
The ratio of instantaneous event rates between groups; 0.7 means a 30% lower rate at any moment.
hr_1_low
A range of effect values compatible with your data at the chosen confidence level.
hr_1_high
A range of effect values compatible with your data at the chosen confidence level.
p_1
How surprising your data would be if the null hypothesis were true, as a probability.
epv
Events (the rarer outcome) per estimated coefficient in logistic or Cox models.
se_type
Standard errors that stay valid when residual variance is not constant; HC3 suits small samples.
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: 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(Surv(start, stop, event) ~ …, cluster = id) with tt() terms; Python maximizes the same Efron/Breslow partial likelihood by Newton's method (codesplash.stats.survival_adv.cox_cp, with weighted risk sets) on data split at the event times for tt() terms, and computes the same robust variance from score residuals. Agreement ≈ 1e-10.
Python

The exact script CodeSplash ran for example “Heart transplant” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Cox model with time-varying covariates (start–stop data)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cox_tv 1.0.1 · spec 876c06fff1bf27f1
# Dataset: s2_heart (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_adv as sa  # coxph for (start, stop] data: Efron/Breslow, strata, robust SEs

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s2_heart.parquet", columns=["start", "stop", "event", "age", "surgery", "transplant", "id"])
n_input = len(df)
df["surgery"] = pd.Categorical(df["surgery"], categories=["false", "true"])  # stored level order
df["transplant"] = pd.Categorical(df["transplant"], categories=["false", "true"])  # stored level order
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"])  # stored level order
df = df.dropna(subset=["start", "stop", "event", "age", "surgery", "transplant", "id"])  # listwise deletion over the analysis columns
df["surgery"] = df["surgery"].cat.remove_unused_categories()
df["transplant"] = df["transplant"].cat.remove_unused_categories()
df["id"] = df["id"].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, ["start", "stop", "event", "age", "surgery", "transplant", "id"])  # infinite values stop the run (registry/errors.yaml)

# %% Counting-process data: one row per (start, stop] interval
scol = "start"
tcol = "stop"
ecol = "event"
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)

# %% Predictors (time-varying-effect columns are also main effects)
preds = ["age", "surgery", "transplant"]
tv = []
for c in tv:
    if c not in preds:
        preds.append(c)
# %% 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))


def as_number(name):
    s = df[name]
    if isinstance(s.dtype, pd.CategoricalDtype):  # yes/no columns
        return (s.astype(str) == "true").to_numpy(dtype=float)
    return s.to_numpy(dtype=float)


conf = 0.95
ties = "efron"  # pinned: coxph's default is Efron, SAS/Stata use Breslow
tt_function = "log"
idcol = "id"
ids = df[idcol].astype(str).to_numpy()
n_subjects = len(np.unique(ids))
robust = True
# overlapping intervals within a subject and late entry (first start > 0)
order = np.lexsort((t0, ids))
same = ids[order][1:] == ids[order][:-1]
n_overlap = int(np.sum(same & (t0[order][1:] < t1[order][:-1])))
first = np.r_[True, ~same]
n_delayed = int(np.sum(t0[order][first] > 0))
sname = None
scodes = None

# %% Time-varying effects: split the intervals at every event time and add x × g(t) (coxph's tt())
start, stop, event, Xf, rows = t0, t1, ev, X, np.arange(len(t1))
if tv:
    cuts = np.unique(t1[ev])
    if tt_function == "log" and cuts.min() <= 0:
        raise ValueError("log(t) needs event times above zero; choose g(t) = t")
    sp = sa.split_at(t0, t1, ev, cuts)
    rows = sp["row"]
    g_t = np.log(sp["stop"]) if tt_function == "log" else sp["stop"]
    Xf = np.column_stack([X[rows]] + [as_number(c)[rows] * g_t for c in tv])
    start, stop, event = sp["start"], sp["stop"], sp["event"]
    labels = labels + [f"{c} × {'log(t)' if tt_function == 'log' else 't'}" for c in tv]

# %% Cox model
fit = sa.cox_cp(start, stop, event, Xf, strata=None if scodes is None else scodes[rows], ties=ties,
                cluster=ids[rows] if robust else None)
beta = fit["coef"]
naive_se = np.sqrt(np.diag(fit["cov"]))
V = fit["rcov"] if robust else fit["cov"]
se = np.sqrt(np.diag(V))
z = beta / se
pv = 2 * stats.norm.sf(np.abs(z))
q = stats.norm.ppf(1 - (1 - conf) / 2)
hr, hr_lo, hr_hi = np.exp(beta), np.exp(beta - q * se), np.exp(beta + q * se)
k = len(beta)
lr_p = float(stats.chi2.sf(fit["lr"], k))
wald = float(beta @ np.linalg.solve(V, beta))
se_type = "robust (clustered by subject)" if robust else "model-based"

values = {
    "n_rows": float(len(t1)), "n_subjects": float(n_subjects), "n_delayed": float(n_delayed), "events": float(ev.sum()),
    "n_coef": float(k), "n_tt": float(len(tv)), "loglik": fit["loglik"], "loglik0": fit["loglik0"],
    "lr_chisq": fit["lr"], "lr_df": float(k), "lr_p": lr_p, "wald_chisq": wald, "wald_p": float(stats.chi2.sf(wald, k)),
    "score_chisq": fit["score"], "score_p": float(stats.chi2.sf(fit["score"], 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]),
    "epv": float(ev.sum()) / k, "se_type": se_type, "event_label": event_label,
}
coef_rows = []
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])})

# %% Assumptions
epv = values["epv"]
assumptions = [
    {"key": "events_per_variable", "label": "Events per variable", "status": "warn" if epv < 10 else "pass",
     "detail": f"{epv:.1f} events per coefficient" + (" — fewer than 10; estimates may be biased and unstable." if epv < 10 else ".")},
    {"key": "intervals", "label": "Non-overlapping intervals", "status": "fail" if n_overlap else ("pass" if ids is not None else "info"),
     "detail": (f"{n_overlap} intervals overlap the subject's previous interval — fix the data before interpreting the model." if n_overlap
                else "Intervals of each subject do not overlap." if ids is not None else "Without a subject id the intervals cannot be checked per subject.")},
    {"key": "censoring", "label": "Non-informative censoring and entry", "status": "info",
     "detail": f"{int((~ev).sum())} of {len(ev)} intervals end without the event; {n_delayed} subjects enter after time 0 (delayed entry is handled by the risk sets)."},
]

# %% Result
pct = f"{conf:.0%}"
cs.publish({
    "method": "survival.cox_tv",
    "methodVersion": "1.0.1",
    "title": "Cox model with time-varying covariates",
    "engine": cs.engine_info("numpy", "scipy", "codesplash"),
    "n": int(n_subjects),
    "summary": f"Cox model for start–stop data ({int(ev.sum())} events, {len(t1)} intervals): likelihood-ratio χ²({k}) = {fit['lr']:.2f}, {cs.fmt_p(lr_p)}.",
    "apa": f"HR = {cs.fmt_num(hr[0])}, {pct} CI [{cs.fmt_num(hr_lo[0])}, {cs.fmt_num(hr_hi[0])}], {cs.fmt_p(pv[0])}",
    "statistics": [
        {"key": "lr_chisq", "label": "Likelihood-ratio χ²", "value": fit["lr"]}, {"key": "lr_df", "label": "df", "value": float(k), "format": "integer"},
        {"key": "lr_p", "label": "p", "value": lr_p, "format": "p"}, {"key": "events", "label": "Events", "value": float(ev.sum()), "format": "integer"},
    ],
    "tables": [
        {"key": "coefficients", "title": "Hazard ratios", "columns": [
            {"key": "term", "label": "Term", "type": "string"}, {"key": "coef", "label": "β", "type": "number"},
            {"key": "se", "label": "SE", "type": "number"}, {"key": "hr", "label": "HR", "type": "number"},
            {"key": "hr_low", "label": f"{pct} CI low", "type": "number"}, {"key": "hr_high", "label": f"{pct} CI high", "type": "number"},
            {"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
        ], "rows": coef_rows, "note": f"Standard errors: {se_type}."},
        {"key": "tests", "title": "Overall tests", "columns": [
            {"key": "test", "label": "Test", "type": "string"}, {"key": "chisq", "label": "χ²", "type": "number"},
            {"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"},
        ], "rows": [
            {"test": "Likelihood ratio", "chisq": fit["lr"], "df": float(k), "p": lr_p},
            {"test": "Wald" + (" (robust)" if robust else ""), "chisq": wald, "df": float(k), "p": values["wald_p"]},
            {"test": "Score", "chisq": fit["score"], "df": float(k), "p": values["score_p"]},
        ]},
    ],
    "effectSizes": [{"key": "hr_1", "label": f"Hazard ratio ({labels[0]})", "value": float(hr[0]), "ciLow": float(hr_lo[0]),
                     "ciHigh": float(hr_hi[0]), "ciLevel": conf, "method": f"Wald interval on log(HR), {se_type} SE"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Event: {event_label}. Ties: {ties}." + (f" Stratified by {sname}." if sname else "")
              + (f" Time-varying effects: {', '.join(tv)} × {'log(t)' if tt_function == 'log' else 't'}." if tv else "")],
    "charts": [
        cs.chart("hr", "forest", "Hazard ratios", {
            "label": cs.col("Term", labels, "categorical", levels=labels), "estimate": cs.col("Hazard ratio", hr, "numeric"),
            "low": cs.col("lower", hr_lo, "numeric"), "high": cs.col("upper", hr_hi, "numeric"),
        }, controls={"reference": 1, "log": True}),
    ],
    "values": values,
})
R

The exact script CodeSplash ran for example “Heart transplant” · R version 4.5.1 (2025-06-13)

# Cox model with time-varying covariates (start–stop data)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.cox_tv 1.0.1 · spec 876c06fff1bf27f1
# Dataset: s2_heart (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_heart.parquet", col_select = c("start", "stop", "event", "age", "surgery", "transplant", "id")))
n_input <- nrow(df)
df[["surgery"]] <- factor(df[["surgery"]], levels = c("false", "true"))  # stored level order
df[["transplant"]] <- factor(df[["transplant"]], levels = c("false", "true"))  # stored level order
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"))  # stored level order
df <- df[stats::complete.cases(df[c("start", "stop", "event", "age", "surgery", "transplant", "id")]), , 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("start", "stop", "event", "age", "surgery", "transplant", "id"))  # infinite values stop the run (registry/errors.yaml)

# %% Counting-process data: one row per (start, stop] interval
scol <- "start"
tcol <- "stop"
ecol <- "event"
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)

# %% Predictors (time-varying-effect columns are also main effects)
preds <- c("age", "surgery", "transplant")
tv <- c()
preds <- c(preds, setdiff(tv, preds))
dd <- data.frame(.start = t0, .stop = t1, .e = ev)
# %% 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"
as_number <- function(x) if (is.factor(x)) as.numeric(as.character(x) == "true") else as.numeric(x)  # yes/no columns

conf <- 0.95
ties <- "efron"  # pinned: coxph's default is Efron, SAS/Stata use Breslow
tt_function <- "log"
idcol <- "id"
ids <- as.character(df[[idcol]])
dd$.id <- ids
n_subjects <- length(unique(ids))
robust <- TRUE
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)]))
first <- c(TRUE, !same)
n_delayed <- sum(t0[o][first] > 0)
sname <- NULL

# %% Time-varying effects: coxph's tt() evaluates x × g(t) at every event time
tt_names <- character(0)
for (i in seq_along(tv)) {
  nm <- sprintf(".tt%d", i)
  dd[[nm]] <- as_number(df[[tv[i]]])
  tt_names <- c(tt_names, nm)
}
if (length(tv)) {
  rhs <- paste(rhs, "+", paste(sprintf("tt(%s)", tt_names), collapse = " + "))
  labels <- c(labels, sprintf("%s × %s", tv, if (tt_function == "log") "log(t)" else "t"))
  if (tt_function == "log" && min(t1[ev]) <= 0) stop("log(t) needs event times above zero; choose g(t) = t")
}
tt_fun <- if (tt_function == "log") function(x, t, ...) x * log(t) else function(x, t, ...) x * t

# %% Cox model
ctl <- coxph.control(eps = 1e-12, toler.chol = 1e-15, iter.max = 60)
form <- stats::as.formula(paste("Surv(.start, .stop, .e) ~", rhs))
fit <- if (robust) coxph(form, data = dd, ties = ties, tt = tt_fun, cluster = .id, control = ctl) else
  coxph(form, data = dd, ties = ties, tt = tt_fun, 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(if (robust) unname(fit$naive.var) else V))
se <- sqrt(diag(V))
z <- beta / se
pv <- 2 * stats::pnorm(-abs(z))
q <- stats::qnorm(1 - (1 - conf) / 2)
hr <- exp(beta)
hr_lo <- exp(beta - q * se)
hr_hi <- exp(beta + q * se)
k <- length(beta)
lr <- 2 * diff(fit$loglik)
lr_p <- stats::pchisq(lr, k, lower.tail = FALSE)
wald <- drop(beta %*% solve(V, beta))
score <- unname(fit$score)
se_type <- if (robust) "robust (clustered by subject)" else "model-based"

values <- list(
  n_rows = length(t1), n_subjects = n_subjects, n_delayed = n_delayed, events = sum(ev), n_coef = k, n_tt = length(tv),
  loglik = fit$loglik[2], loglik0 = fit$loglik[1], lr_chisq = lr, lr_df = k, lr_p = lr_p,
  wald_chisq = wald, wald_p = stats::pchisq(wald, k, lower.tail = FALSE),
  score_chisq = score, score_p = stats::pchisq(score, k, lower.tail = FALSE),
  coef_1_label = labels[1], hr_1 = hr[1], hr_1_low = hr_lo[1], hr_1_high = hr_hi[1], p_1 = pv[1],
  epv = sum(ev) / k, se_type = se_type, event_label = event_label
)
coef_rows <- list()
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")])
}

# %% Assumptions
epv <- values$epv
assumptions <- list(
  list(key = "events_per_variable", label = "Events per variable", status = if (epv < 10) "warn" else "pass",
       detail = paste0(sprintf("%.1f events per coefficient", epv), if (epv < 10) " — fewer than 10; estimates may be biased and unstable." else ".")),
  list(key = "intervals", label = "Non-overlapping intervals",
       status = if (n_overlap > 0) "fail" else if (TRUE) "pass" else "info",
       detail = if (n_overlap > 0) sprintf("%d intervals overlap the subject's previous interval — fix the data before interpreting the model.", n_overlap)
                else if (TRUE) "Intervals of each subject do not overlap."
                else "Without a subject id the intervals cannot be checked per subject."),
  list(key = "censoring", label = "Non-informative censoring and entry", status = "info",
       detail = sprintf("%d of %d intervals end without the event; %d subjects enter after time 0 (delayed entry is handled by the risk sets).",
                        sum(!ev), length(ev), n_delayed))
)

# %% Result
pct <- sprintf("%.0f%%", conf * 100)
cs_publish(list(
  method = "survival.cox_tv",
  methodVersion = "1.0.1",
  title = "Cox model with time-varying covariates",
  engine = cs_engine_info("survival", "codesplashr"),
  n = n_subjects,
  summary = sprintf("Cox model for start–stop data (%d events, %d intervals): likelihood-ratio χ²(%d) = %.2f, %s.", sum(ev), length(t1), k, lr, cs_fmt_p(lr_p)),
  apa = sprintf("HR = %s, %s CI [%s, %s], %s", cs_fmt_num(hr[1]), pct, cs_fmt_num(hr_lo[1]), cs_fmt_num(hr_hi[1]), cs_fmt_p(pv[1])),
  statistics = list(
    list(key = "lr_chisq", label = "Likelihood-ratio χ²", value = lr), list(key = "lr_df", label = "df", value = k, format = "integer"),
    list(key = "lr_p", label = "p", value = lr_p, format = "p"), list(key = "events", label = "Events", value = sum(ev), format = "integer")
  ),
  tables = list(
    list(key = "coefficients", title = "Hazard ratios", columns = list(
      list(key = "term", label = "Term", type = "string"), list(key = "coef", label = "β", type = "number"),
      list(key = "se", label = "SE", type = "number"), list(key = "hr", label = "HR", type = "number"),
      list(key = "hr_low", label = paste(pct, "CI low"), type = "number"), list(key = "hr_high", label = paste(pct, "CI high"), type = "number"),
      list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue")
    ), rows = coef_rows, note = sprintf("Standard errors: %s.", se_type)),
    list(key = "tests", title = "Overall tests", columns = list(
      list(key = "test", label = "Test", type = "string"), list(key = "chisq", label = "χ²", type = "number"),
      list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")
    ), rows = list(
      list(test = "Likelihood ratio", chisq = lr, df = k, p = lr_p),
      list(test = if (robust) "Wald (robust)" else "Wald", chisq = wald, df = k, p = values$wald_p),
      list(test = "Score", chisq = score, df = k, p = values$score_p)
    ))
  ),
  effectSizes = list(list(key = "hr_1", label = sprintf("Hazard ratio (%s)", labels[1]), value = hr[1], ciLow = hr_lo[1],
                          ciHigh = hr_hi[1], ciLevel = conf, method = sprintf("Wald interval on log(HR), %s SE", se_type))),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(paste0(sprintf("Event: %s. Ties: %s.", event_label, ties), if (!is.null(sname)) sprintf(" Stratified by %s.", sname) else "",
                      if (length(tv)) sprintf(" Time-varying effects: %s × %s.", paste(tv, collapse = ", "), if (tt_function == "log") "log(t)" else "t") else "")),
  charts = list(
    cs_chart("hr", "forest", "Hazard ratios", list(
      label = cs_col("Term", labels, "categorical", levels = labels), estimate = cs_col("Hazard ratio", hr, "numeric"),
      low = cs_col("lower", hr_lo, "numeric"), high = cs_col("upper", hr_hi, "numeric")
    ), controls = list(reference = 1, log = TRUE))
  ),
  values = values
))

Sources

  • Andersen, P. K., & Gill, R. D. (1982). Cox's regression model for counting processes: A large sample study. Annals of Statistics, 10, 1100–1120.
  • Therneau, T. M., & Grambsch, P. M. (2000). Modeling survival data: Extending the Cox model. Springer.
  • Lin, D. Y., & Wei, L. J. (1989). The robust inference for the Cox proportional hazards model. JASA, 84, 1074–1078.
  • Therneau, T., Crowson, C., & Atkinson, E. (2024). Using time dependent covariates and time dependent coefficients in the Cox model. survival package vignette.

From the CodeSplash method registry · survival.cox_tv v1.0.1.