When curves cross: Rényi, max-combo and restricted means
A log-rank test can miss a real difference when early and late effects cancel. Learn three pre-specifiable alternatives and what each one answers.
What runs in CodeSplash
- STAT245Rényi supremum survival tests Runs in CodeSplash
- Log-rank test (compare survival curves) Verified in Python and R
You will be able to
- Explain why opposing early and late effects can cancel in a log-rank test
- Choose among the Rényi supremum test, max-combo and a restricted mean difference
- Report a restricted mean difference with its horizon and interval
How a real difference can vanish
ReadThe log-rank statistic adds up observed minus expected events over time. If one group does worse early and better late, those contributions have opposite signs:
So you can have two plainly different curves and a large p-value. That isn't evidence that the groups are alike.
Make the hazards cross
ExploreChoose crossing hazards under Break it, or set the two shapes apart. One group starts safer and ends riskier.
FExplorable · From hazard to survival
How does the moment-to-moment risk build up into a survival curve?
What share of group A is still event-free at this time?
Below 1 risk falls with time; above 1 it rises.
Hazard: risk at each moment
Survival: still event-free
Commit your prediction above to see the result
Make your prediction to see the result.
Read the hazard ratio at different times. If it changes side of 1, no single hazard ratio describes these groups. A Cox model would report one anyway: an average of opposite effects.
Largest gap, not total gap
ReadThe Rényi supremum testRényi supremum testCompares two survival curves by the largest gap the score process reaches, so a difference that later reverses still counts. doesn't wait until the end to add things up. It follows the running sum over time and uses the largest distance it reaches:
A gap that opens and later closes still counts. Because you're taking a maximum over time, the p-value comes from the running maximum of a Brownian motion, not a plain normal table.
Three tests, one dataset
PredictPredict first
In the lung data, women and men separate early and stay apart, with no crossing. Log-rank gives p = .001.
How will the Rényi test compare, when hazards don't cross?
Reveal
They agree closely: the Rényi test gives Q = 3.48, p = .001. When hazards are roughly proportional the alternatives add little. Their value is that they keep their power when the pattern is less tidy.
Max-combo
In the appThe max-combo testMax-combo testThe largest of four Fleming–Harrington tests, for early, late, middle and constant differences; its p-value allows for the choice. runs four Fleming–Harrington tests at once, FH(0,0), FH(0,1), FH(1,0) and FH(1,1), which suit constant, late, early and middle differences. It takes the largest and corrects for having looked four times, so its p-value already accounts for the choice.
Largest = 3.57, p < .001.
max |Z| = 3.57, p < .001
- Largest |Z|
- 3.566
- p
- < .001
- Log-rank p
- .001
Plots
View data
| upper | lower | Censored | At risk | sex | Survival probability | time |
|---|---|---|---|---|---|---|
| 1 | 1 | 0 | 138 | male | 1 | 0 |
| 0.9929 | 0.9341 | 0 | 138 | male | 0.9783 | 11 |
| 0.9890 | 0.9246 | 0 | 135 | male | 0.9710 | 12 |
| 0.9802 | 0.9058 | 0 | 134 | male | 0.9565 | 13 |
| 0.9755 | 0.8965 | 0 | 132 | male | 0.9493 | 15 |
| 0.9706 | 0.8874 | 0 | 131 | male | 0.9420 | 26 |
| 0.9655 | 0.8784 | 0 | 130 | male | 0.9348 | 30 |
| 0.9603 | 0.8695 | 0 | 129 | male | 0.9275 | 31 |
| 0.9497 | 0.8520 | 0 | 128 | male | 0.9130 | 53 |
| 0.9442 | 0.8433 | 0 | 126 | male | 0.9058 | 54 |
| 0.9386 | 0.8347 | 0 | 125 | male | 0.8986 | 59 |
| 0.9330 | 0.8262 | 0 | 124 | male | 0.8913 | 60 |
| 0.9216 | 0.8093 | 0 | 123 | male | 0.8768 | 65 |
| 0.9157 | 0.8010 | 0 | 121 | male | 0.8696 | 71 |
| 0.9099 | 0.7927 | 0 | 120 | male | 0.8623 | 81 |
| 0.8980 | 0.7762 | 0 | 119 | male | 0.8478 | 88 |
| 0.8920 | 0.7681 | 0 | 117 | male | 0.8406 | 92 |
| 0.8860 | 0.7599 | 0 | 116 | male | 0.8333 | 93 |
| 0.8799 | 0.7519 | 0 | 115 | male | 0.8261 | 95 |
| 0.8737 | 0.7438 | 0 | 114 | male | 0.8188 | 105 |
| 0.8676 | 0.7358 | 0 | 113 | male | 0.8116 | 107 |
| 0.8614 | 0.7278 | 0 | 112 | male | 0.8043 | 110 |
| 0.8552 | 0.7199 | 0 | 111 | male | 0.7971 | 116 |
| 0.8489 | 0.7119 | 0 | 110 | male | 0.7899 | 118 |
| 0.8426 | 0.7041 | 0 | 109 | male | 0.7826 | 131 |
| 0.8300 | 0.6884 | 0 | 108 | male | 0.7681 | 132 |
| 0.8236 | 0.6806 | 0 | 106 | male | 0.7609 | 135 |
| 0.8172 | 0.6728 | 0 | 105 | male | 0.7536 | 142 |
| 0.8108 | 0.6650 | 0 | 104 | male | 0.7464 | 144 |
| 0.8043 | 0.6573 | 0 | 103 | male | 0.7391 | 147 |
| 0.7913 | 0.6419 | 0 | 102 | male | 0.7246 | 156 |
| 0.7717 | 0.6191 | 0 | 100 | male | 0.7029 | 163 |
| 0.7651 | 0.6115 | 0 | 97 | male | 0.6957 | 166 |
| 0.7585 | 0.6039 | 0 | 96 | male | 0.6884 | 170 |
| 0.7585 | 0.6039 | 1 | 95 | male | 0.6884 | 174 |
| 0.7518 | 0.5963 | 0 | 94 | male | 0.6811 | 175 |
| 0.7451 | 0.5887 | 0 | 93 | male | 0.6738 | 176 |
| 0.7383 | 0.5811 | 0 | 92 | male | 0.6664 | 177 |
| 0.7248 | 0.5659 | 0 | 91 | male | 0.6518 | 179 |
| 0.7180 | 0.5584 | 0 | 89 | male | 0.6445 | 180 |
| 0.7044 | 0.5434 | 0 | 88 | male | 0.6298 | 181 |
| 0.6975 | 0.5359 | 0 | 86 | male | 0.6225 | 183 |
| 0.6975 | 0.5359 | 1 | 85 | male | 0.6225 | 185 |
| 0.6975 | 0.5359 | 1 | 84 | male | 0.6225 | 188 |
| 0.6905 | 0.5283 | 0 | 83 | male | 0.6150 | 189 |
| 0.6905 | 0.5283 | 1 | 82 | male | 0.6150 | 191 |
| 0.6905 | 0.5283 | 1 | 81 | male | 0.6150 | 196 |
| 0.6833 | 0.5204 | 1 | 80 | male | 0.6073 | 197 |
| 0.6760 | 0.5124 | 0 | 78 | male | 0.5995 | 202 |
| 0.6687 | 0.5045 | 0 | 77 | male | 0.5917 | 207 |
| 0.6614 | 0.4966 | 0 | 76 | male | 0.5839 | 210 |
| 0.6541 | 0.4887 | 0 | 75 | male | 0.5762 | 212 |
| 0.6467 | 0.4808 | 0 | 74 | male | 0.5684 | 218 |
| 0.6467 | 0.4808 | 1 | 73 | male | 0.5684 | 221 |
| 0.6392 | 0.4728 | 1 | 72 | male | 0.5605 | 222 |
| 0.6316 | 0.4648 | 0 | 70 | male | 0.5525 | 223 |
| 0.6316 | 0.4648 | 2 | 69 | male | 0.5525 | 225 |
| 0.6238 | 0.4564 | 0 | 67 | male | 0.5442 | 229 |
| 0.6160 | 0.4481 | 0 | 66 | male | 0.5360 | 230 |
| 0.6160 | 0.4481 | 1 | 65 | male | 0.5360 | 237 |
First 60 of 208 rows.
View data
| sex | Survival probability | time |
|---|---|---|
| male | 1 | 0 |
| male | 0.9783 | 11 |
| male | 0.9710 | 12 |
| male | 0.9565 | 13 |
| male | 0.9493 | 15 |
| male | 0.9420 | 26 |
| male | 0.9348 | 30 |
| male | 0.9275 | 31 |
| male | 0.9130 | 53 |
| male | 0.9058 | 54 |
| male | 0.8986 | 59 |
| male | 0.8913 | 60 |
| male | 0.8768 | 65 |
| male | 0.8696 | 71 |
| male | 0.8623 | 81 |
| male | 0.8478 | 88 |
| male | 0.8406 | 92 |
| male | 0.8333 | 93 |
| male | 0.8261 | 95 |
| male | 0.8188 | 105 |
| male | 0.8116 | 107 |
| male | 0.8043 | 110 |
| male | 0.7971 | 116 |
| male | 0.7899 | 118 |
| male | 0.7826 | 131 |
| male | 0.7681 | 132 |
| male | 0.7609 | 135 |
| male | 0.7536 | 142 |
| male | 0.7464 | 144 |
| male | 0.7391 | 147 |
| male | 0.7246 | 156 |
| male | 0.7029 | 163 |
| male | 0.6957 | 166 |
| male | 0.6884 | 170 |
| male | 0.6884 | 174 |
| male | 0.6811 | 175 |
| male | 0.6738 | 176 |
| male | 0.6664 | 177 |
| male | 0.6518 | 179 |
| male | 0.6445 | 180 |
| male | 0.6298 | 181 |
| male | 0.6225 | 183 |
| male | 0.6225 | 185 |
| male | 0.6225 | 188 |
| male | 0.6150 | 189 |
| male | 0.6150 | 191 |
| male | 0.6150 | 196 |
| male | 0.6073 | 197 |
| male | 0.5995 | 202 |
| male | 0.5917 | 207 |
| male | 0.5839 | 210 |
| male | 0.5762 | 212 |
| male | 0.5684 | 218 |
| male | 0.5684 | 221 |
| male | 0.5605 | 222 |
| male | 0.5525 | 223 |
| male | 0.5525 | 225 |
| male | 0.5442 | 229 |
| male | 0.5360 | 230 |
| male | 0.5360 | 237 |
First 60 of 208 rows.
Assumptions
- Proportional hazards — Grambsch–Therneau test χ²(1) = 2.86, p = .091: no evidence that hazard ratios change over time.
- Non-informative censoring — 63 of 228 observations are censored.
- Number of events — At least 5 events per group.
Observed and expected events
| sex | n | Events | Observed (weighted) | Expected (weighted) | (O−E)²/E |
|---|---|---|---|---|---|
| male | 138 | 112 | 112 | 91.582 | 4.552 |
| female | 90 | 53 | 53 | 73.418 | 5.678 |
Fleming–Harrington components
| Test | Z |
|---|---|
| FH(0, 0) | 3.214 |
| FH(0, 1) | 1.860 |
| FH(1, 0) | 3.566 |
| FH(1, 1) | 2.769 |
FH(ρ, γ) weights S(t−)^ρ (1 − S(t−))^γ. The p-value allows for taking the largest of the four.
- Event: dead = true. The four tests take their weights from the pooled Kaplan–Meier curve.
The exact R script · R R version 4.5.1 (2025-06-13)
# Log-rank test (compare survival curves)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.logrank 1.2.1 · spec 89364675d8ed640d
# Dataset: lung (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(survival)
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/lung.parquet", col_select = c("time", "dead", "sex")))
n_input <- nrow(df)
df[["dead"]] <- factor(df[["dead"]], levels = c("false", "true")) # stored level order
df[["sex"]] <- factor(df[["sex"]], levels = c("male", "female")) # stored level order
df <- df[stats::complete.cases(df[c("time", "dead", "sex")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("time", "dead", "sex")) # infinite values stop the run (registry/errors.yaml)
# %% Event coding
tcol <- "time"
ecol <- "dead"
tt <- as.numeric(df[[tcol]])
if (any(tt < 0)) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = "zero or positive (survival times)", count = sum(tt < 0))
event_level <- "true" # the event; other levels are censored
ev <- as.character(df[[ecol]]) == event_level
event_label <- sprintf("%s = %s", ecol, event_level)
if (!any(ev)) cs_error("CS_E_NO_EVENTS", event = event_label)
# %% Log-rank test
g <- "sex"
levels_g <- levels(df[[g]])
if (length(levels_g) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = length(levels_g))
gv <- factor(as.character(df[[g]]), levels = levels_g)
sname <- NULL
sv <- NULL
weights <- "logrank"
rho <- switch(weights, logrank = 0, peto = 1, fh = 0.5, 0) # survdiff(rho = …)
gamma <- if (weights == "fh") 0 else 0 # Fleming–Harrington (1 − S(t−))^γ; survdiff has γ = 0 only
use_survdiff <- weights %in% c("logrank", "peto") || (weights == "fh" && gamma == 0)
weight_note <- switch(weights,
gehan = "weights n(t), the number at risk", tarone_ware = "weights √n(t)",
peto_prentice = "weights S̃(t) = Π(1 − d/(n + 1)) (Peto's survival estimate)",
modified_peto = "weights S̃(t)·n/(n + 1) (Andersen et al.)",
if (gamma != 0) sprintf("weights S(t−)^ρ (1 − S(t−))^γ with ρ = %s, γ = %s, from the pooled Kaplan–Meier curve", format(rho), format(gamma))
else sprintf("weights S(t−)^ρ with ρ = %s from the pooled Kaplan–Meier curve", format(rho)))
lr_test <- function(tt, ee, gg, ss) {
# survdiff where it applies; codesplashr's weighted log-rank for Gehan, Tarone–Ware, Peto–Prentice and FH(ρ, γ)
if (use_survdiff) {
r <- if (is.null(ss)) survdiff(Surv(tt, ee) ~ gg, rho = rho) else survdiff(Surv(tt, ee) ~ gg + strata(ss), rho = rho)
list(obs = if (is.matrix(r$obs)) rowSums(r$obs) else r$obs, exp = if (is.matrix(r$exp)) rowSums(r$exp) else r$exp, chisq = r$chisq)
} else {
cs_surv_logrank(tt, ee, gg, ss, weights = weights, rho = rho, gamma = gamma)
}
}
test_label <- switch(weights, logrank = "The log-rank test", peto = "The Peto–Peto weighted log-rank test (ρ = 1)",
gehan = "The Gehan–Breslow (generalized Wilcoxon) test", tarone_ware = "The Tarone–Ware test",
peto_prentice = "The Peto–Prentice test", modified_peto = "The modified Peto–Peto (Andersen) test",
if (gamma != 0) sprintf("The Fleming–Harrington G(ρ = %s, γ = %s) test", format(rho), format(gamma))
else sprintf("The Fleming–Harrington G-ρ test (ρ = %s)", format(rho)))
if (!is.null(sname)) test_label <- sprintf("%s, stratified by %s,", test_label, sname)
lr <- lr_test(tt, ev, gv, sv)
obs <- lr$obs
expd <- lr$exp
chisq <- lr$chisq
dof <- length(levels_g) - 1
p <- stats::pchisq(chisq, dof, lower.tail = FALSE)
values <- list(chisq = chisq, df = dof, p = p, n = length(tt), events = sum(ev), n_groups = length(levels_g), rho = rho, gamma = gamma,
event_label = event_label, test_label = test_label)
rows <- list()
for (i in seq_along(levels_g)) {
lv <- levels_g[i]
m <- gv == lv
values[[sprintf("n[%s]", lv)]] <- sum(m)
values[[sprintf("events[%s]", lv)]] <- sum(ev[m])
values[[sprintf("obs[%s]", lv)]] <- unname(obs[i])
values[[sprintf("exp[%s]", lv)]] <- unname(expd[i])
rows[[i]] <- list(group = lv, n = sum(m), events = sum(ev[m]), obs = unname(obs[i]), exp = unname(expd[i]),
oe = unname((obs[i] - expd[i])^2 / expd[i]))
}
# %% Pairwise comparisons
pair_rows <- list()
if (TRUE && length(levels_g) > 2) {
pairs <- utils::combn(length(levels_g), 2, simplify = FALSE)
raw <- lapply(pairs, function(ab) {
m <- gv %in% levels_g[ab]
gg <- factor(as.character(gv[m]), levels = levels_g[ab])
r <- lr_test(tt[m], ev[m], gg, if (is.null(sv)) NULL else sv[m])
c(r$chisq, stats::pchisq(r$chisq, 1, lower.tail = FALSE))
})
adj <- cs_p_adjust(vapply(raw, `[`, numeric(1), 2), "holm")
for (i in seq_along(pairs)) {
key <- sprintf("%s vs %s", levels_g[pairs[[i]][1]], levels_g[pairs[[i]][2]])
values[[sprintf("chisq_pair[%s]", key)]] <- raw[[i]][1]
values[[sprintf("p_pair[%s]", key)]] <- raw[[i]][2]
values[[sprintf("p_pair_adj[%s]", key)]] <- adj[i]
pair_rows[[i]] <- list(pair = key, chisq = raw[[i]][1], p = raw[[i]][2], p_adj = adj[i])
}
}
# %% Two-group alternatives: supremum, max-combo, restricted mean survival time
test_kind <- "max_combo"
values[c("logrank_p", "test_kind", "renyi_q", "renyi_max_u", "renyi_var", "combo_max_z", "tau", "rmst_diff", "rmst_diff_se", "rmst_diff_low", "rmst_diff_high", "rmst_z")] <-
list(p, test_kind, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)
if (test_kind != "chisq" && length(levels_g) != 2) stop(sprintf("This test compares exactly two groups; %s has %d", g, length(levels_g)))
extra_tables <- list()
statistics <- list(list(key = "chisq", label = "χ²", value = chisq), list(key = "df", label = "df", value = dof, format = "integer"), list(key = "p", label = "p", value = p, format = "p"))
summary_text <- sprintf("%s χ²(%d) = %.2f, %s.", test_label, dof, chisq, cs_fmt_p(p))
apa_text <- sprintf("χ²(%d, N = %d) = %s, %s", dof, length(tt), cs_fmt_num(chisq), cs_fmt_p(p))
rmst_tau <- NULL
if (test_kind == "renyi") {
rn <- cs_surv_renyi(tt, ev, gv, sv, weights = weights, rho = rho, gamma = gamma)
p <- rn$p
test_label <- paste0("The Rényi supremum test", if (!is.null(sname)) sprintf(", stratified by %s,", sname) else "")
values$p <- p
values$renyi_q <- rn$q
values$renyi_max_u <- rn$max_u
values$renyi_var <- rn$var
values$test_label <- test_label
statistics <- list(list(key = "renyi_q", label = "Q", value = rn$q), list(key = "p", label = "p", value = p, format = "p"),
list(key = "logrank_p", label = "Log-rank p", value = values$logrank_p, format = "p"))
summary_text <- sprintf("%s: Q = %.3f, %s.", sub(",$", "", test_label), rn$q, cs_fmt_p(p))
apa_text <- sprintf("Q = %s, %s", cs_fmt_num(rn$q), cs_fmt_p(p))
} else if (test_kind == "max_combo") {
mc <- cs_surv_max_combo(tt, ev, gv, sv, reps = as.integer(4999), seed = 42)
p <- mc$p
test_label <- paste0("The max-combo test", if (!is.null(sname)) sprintf(", stratified by %s,", sname) else "")
values$p <- p
values$combo_max_z <- mc$max_z
values$test_label <- test_label
combo_rows <- list()
for (i in seq_along(mc$labels)) {
values[[sprintf("combo_z[%s]", mc$labels[i])]] <- mc$z[i]
combo_rows[[i]] <- list(test = mc$labels[i], z = mc$z[i])
}
extra_tables[[1]] <- list(key = "combo", title = "Fleming–Harrington components", columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "z", label = "Z", type = "number")), rows = combo_rows,
note = "FH(ρ, γ) weights S(t−)^ρ (1 − S(t−))^γ. The p-value allows for taking the largest of the four.")
statistics <- list(list(key = "combo_max_z", label = "Largest |Z|", value = mc$max_z), list(key = "p", label = "p", value = p, format = "p"),
list(key = "logrank_p", label = "Log-rank p", value = values$logrank_p, format = "p"))
summary_text <- sprintf("%s: largest |Z| = %.3f, %s.", sub(",$", "", test_label), mc$max_z, cs_fmt_p(p))
apa_text <- sprintf("max |Z| = %s, %s", cs_fmt_num(mc$max_z), cs_fmt_p(p))
} else if (test_kind == "rmst") {
if (!is.null(sname)) stop("The restricted mean survival difference does not take strata")
rmst_tau <- min(vapply(levels_g, function(lv) max(tt[gv == lv]), numeric(1))) # horizon
rms <- list()
rm_rows <- list()
for (i in seq_along(levels_g)) {
lv <- levels_g[i]
m <- gv == lv
tb <- summary(survfit(Surv(tt[m], ev[m]) ~ 1), rmean = rmst_tau)$table
rms[[i]] <- c(unname(tb[["rmean"]]), unname(tb[["se(rmean)"]]))
values[[sprintf("rmst[%s]", lv)]] <- rms[[i]][1]
values[[sprintf("rmst_se[%s]", lv)]] <- rms[[i]][2]
rm_rows[[i]] <- list(group = lv, rmst = rms[[i]][1], se = rms[[i]][2])
}
diff_r <- rms[[2]][1] - rms[[1]][1]
se_d <- sqrt(rms[[1]][2]^2 + rms[[2]][2]^2)
zv <- diff_r / se_d
p <- 2 * stats::pnorm(abs(zv), lower.tail = FALSE)
q_ <- stats::qnorm(0.975)
test_label <- "The restricted mean survival time comparison"
values$p <- p
values$tau <- rmst_tau
values$rmst_diff <- diff_r
values$rmst_diff_se <- se_d
values$rmst_diff_low <- diff_r - q_ * se_d
values$rmst_diff_high <- diff_r + q_ * se_d
values$rmst_z <- zv
values$test_label <- test_label
extra_tables[[1]] <- list(key = "rmst", title = sprintf("Restricted mean survival time up to %g", rmst_tau), columns = list(
list(key = "group", label = g, type = "string"), list(key = "rmst", label = "RMST", type = "number"), list(key = "se", label = "SE", type = "number")), rows = rm_rows,
note = sprintf("%s minus %s = %.4g, 95%% CI [%.4g, %.4g].", levels_g[2], levels_g[1], diff_r, diff_r - q_ * se_d, diff_r + q_ * se_d))
statistics <- list(list(key = "rmst_diff", label = "RMST difference", value = diff_r), list(key = "tau", label = "Horizon τ", value = rmst_tau),
list(key = "p", label = "p", value = p, format = "p"), list(key = "logrank_p", label = "Log-rank p", value = values$logrank_p, format = "p"))
summary_text <- sprintf("Up to %g, mean event-free time differed by %.3g (%s minus %s), %s.", rmst_tau, diff_r, levels_g[2], levels_g[1], cs_fmt_p(p))
apa_text <- sprintf("RMST difference = %s, 95%% CI [%s, %s], %s", cs_fmt_num(diff_r), cs_fmt_num(diff_r - q_ * se_d), cs_fmt_num(diff_r + q_ * se_d), cs_fmt_p(p))
}
short_title <- sub(",$", "", sub("^The ", "", test_label))
method_note <- switch(test_kind,
rmst = "Each restricted mean is the area under that group's Kaplan–Meier curve up to τ",
max_combo = "The four tests take their weights from the pooled Kaplan–Meier curve",
paste("Test", weight_note))
# %% Assumptions — Grambsch–Therneau test on a Cox model of the groups
ctl <- coxph.control(eps = 1e-12, toler.chol = 1e-15, iter.max = 60)
cox <- if (is.null(sv)) coxph(Surv(tt, ev) ~ gv, ties = "efron", control = ctl) else
coxph(Surv(tt, ev) ~ gv + strata(sv), ties = "efron", control = ctl)
one_time <- length(unique(tt[ev])) < 2 # with every event at one time the proportional-hazards test is undefined
if (one_time) {
warnings <- c(warnings, cs_warning("CS_W_TIES", column = tcol, consequence = "every event happened at the same time, so the proportional-hazards test is not computed."))
ph_chisq <- NA_real_
ph_p <- NA_real_
ph_check <- list(key = "proportional_hazards", label = "Proportional hazards", status = "info", detail = "Not tested: every event happened at the same time.")
} else {
zt <- cox.zph(cox, transform = "km")$table
ph_chisq <- unname(zt["GLOBAL", "chisq"])
ph_p <- unname(zt["GLOBAL", "p"])
ph_check <- list(key = "proportional_hazards", label = "Proportional hazards", status = if (ph_p < 0.05) "warn" else "pass",
statistic = ph_chisq, p = ph_p,
detail = paste0(sprintf("Grambsch–Therneau test χ²(%d) = %.2f, %s: ", dof, ph_chisq, cs_fmt_p(ph_p)),
if (ph_p < 0.05) "hazard ratios change over time; the log-rank test loses power when curves cross."
else "no evidence that hazard ratios change over time."))
}
values$ph_chisq <- ph_chisq
values$ph_p <- ph_p
assumptions <- list(
ph_check,
list(key = "censoring", label = "Non-informative censoring", status = "info",
detail = sprintf("%d of %d observations are censored.", sum(!ev), length(ev)))
)
low <- levels_g[vapply(rows, function(r) r$events < 5, logical(1))]
assumptions[[3]] <- list(key = "sample_size", label = "Number of events", status = if (length(low)) "warn" else "pass",
detail = if (length(low)) sprintf("Fewer than 5 events in %s.", paste(low, collapse = ", ")) else "At least 5 events per group.")
# %% Kaplan–Meier curves for the chart
curve <- list(time = numeric(0), surv = numeric(0), low = numeric(0), high = numeric(0), strata = character(0),
nrisk = numeric(0), ncensor = numeric(0))
for (lv in levels_g) {
m <- gv == lv
fit <- survfit(Surv(tt[m], ev[m]) ~ 1, conf.type = "log-log")
curve$time <- c(curve$time, 0, fit$time)
curve$surv <- c(curve$surv, 1, fit$surv)
curve$low <- c(curve$low, 1, fit$lower)
curve$high <- c(curve$high, 1, fit$upper)
curve$strata <- c(curve$strata, rep(lv, length(fit$time) + 1))
curve$nrisk <- c(curve$nrisk, sum(m), fit$n.risk)
curve$ncensor <- c(curve$ncensor, 0, fit$n.censor)
}
# %% Result
tables <- list(list(key = "groups", title = "Observed and expected events", columns = list(
list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "events", label = "Events", type = "integer"), list(key = "obs", label = "Observed (weighted)", type = "number"),
list(key = "exp", label = "Expected (weighted)", type = "number"), list(key = "oe", label = "(O−E)²/E", type = "number")
), rows = rows))
tables <- c(tables, extra_tables)
if (length(pair_rows)) {
tables[[length(tables) + 1]] <- list(key = "posthoc", title = "Pairwise comparisons", columns = list(
list(key = "pair", label = "Pair", type = "string"), list(key = "chisq", label = "χ²", type = "number"),
list(key = "p", label = "p", type = "pvalue"), list(key = "p_adj", label = "p (adjusted)", type = "pvalue")
), rows = pair_rows, note = "Adjustment: holm.")
}
cs_publish(list(
method = "survival.logrank",
methodVersion = "1.2.1",
title = paste(paste0(toupper(substr(short_title, 1, 1)), substr(short_title, 2, nchar(short_title))), "by", g),
engine = cs_engine_info("survival", "codesplashr"),
n = length(tt),
summary = summary_text,
apa = apa_text,
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Event: %s. %s%s", event_label, method_note,
if (is.null(sname)) "." else sprintf(" within strata of %s.", sname))),
charts = c(list(cs_chart("km", "km-curve", paste("Kaplan–Meier curves by", g), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
low = cs_col("lower", curve$low, "numeric"), high = cs_col("upper", curve$high, "numeric"),
strata = cs_col(g, curve$strata, "categorical", levels = levels_g),
nrisk = cs_col("At risk", curve$nrisk, "numeric"), ncensor = cs_col("Censored", curve$ncensor, "numeric")
)), cs_chart("loglog", "loglog-survival", paste("Log–log survival by", g), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
strata = cs_col(g, curve$strata, "categorical", levels = levels_g)
))), if (!is.null(rmst_tau)) list(cs_chart("rmst", "rmst-area", sprintf("Restricted mean survival up to %g", rmst_tau), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
strata = cs_col(g, curve$strata, "categorical", levels = levels_g)
), controls = list(tau = rmst_tau)))),
values = values
))
max |Z| = 3.57, p < .001
- Largest |Z|
- 3.566
- p
- < .001
- Log-rank p
- .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Proportional hazards — Grambsch–Therneau test χ²(1) = 2.86, p = .091: no evidence that hazard ratios change over time.
- Non-informative censoring — 63 of 228 observations are censored.
- Number of events — At least 5 events per group.
Observed and expected events
| sex | n | Events | Observed (weighted) | Expected (weighted) | (O−E)²/E |
|---|---|---|---|---|---|
| male | 138 | 112 | 112 | 91.582 | 4.552 |
| female | 90 | 53 | 53 | 73.418 | 5.678 |
Fleming–Harrington components
| Test | Z |
|---|---|
| FH(0, 0) | 3.214 |
| FH(0, 1) | 1.860 |
| FH(1, 0) | 3.566 |
| FH(1, 1) | 2.769 |
FH(ρ, γ) weights S(t−)^ρ (1 − S(t−))^γ. The p-value allows for taking the largest of the four.
- Event: dead = true. The four tests take their weights from the pooled Kaplan–Meier curve.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Log-rank test (compare survival curves)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.logrank 1.2.1 · spec 89364675d8ed640d
# Dataset: lung (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
from itertools import combinations
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import survival as sv # survdiff / cox.zph twins
from codesplash.stats import survival_adv as sa # other weights (Gehan, Tarone–Ware, Peto–Prentice, FH(ρ, γ))
from codesplash.stats.padjust import p_adjust
# %% Data
df = pd.read_parquet("tests/parity/fixtures/lung.parquet", columns=["time", "dead", "sex"])
n_input = len(df)
df["dead"] = pd.Categorical(df["dead"], categories=["false", "true"]) # stored level order
df["sex"] = pd.Categorical(df["sex"], categories=["male", "female"]) # stored level order
df = df.dropna(subset=["time", "dead", "sex"]) # listwise deletion over the analysis columns
df["dead"] = df["dead"].cat.remove_unused_categories()
df["sex"] = df["sex"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["time", "dead", "sex"]) # infinite values stop the run (registry/errors.yaml)
# %% Event coding
tcol = "time"
ecol = "dead"
t = df[tcol].to_numpy(dtype=float)
if (t < 0).any():
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement="zero or positive (survival times)", count=int((t < 0).sum()))
event_level = "true" # the event; other levels are censored
ev = (df[ecol].astype(str) == event_level).to_numpy()
event_label = f"{ecol} = {event_level}"
if not ev.any():
cs.cs_error("CS_E_NO_EVENTS", event=event_label)
# %% Log-rank test
g = "sex"
levels = [str(x) for x in df[g].cat.categories]
if len(levels) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=len(levels))
gv = df[g].astype(str).to_numpy()
codes = np.array([levels.index(x) for x in gv])
sname = None
scodes = None
weights = "logrank"
rho = {"logrank": 0.0, "peto": 1.0, "fh": 0.5}.get(weights, 0.0) # survdiff(rho = …)
gamma = 0 if weights == "fh" else 0.0 # Fleming–Harrington (1 − S(t−))^γ; survdiff has γ = 0 only
test_label = {
"logrank": "The log-rank test", "peto": "The Peto–Peto weighted log-rank test (ρ = 1)",
"gehan": "The Gehan–Breslow (generalized Wilcoxon) test", "tarone_ware": "The Tarone–Ware test",
"peto_prentice": "The Peto–Prentice test", "modified_peto": "The modified Peto–Peto (Andersen) test",
}.get(weights, f"The Fleming–Harrington G(ρ = {rho:g}, γ = {gamma:g}) test" if gamma else f"The Fleming–Harrington G-ρ test (ρ = {rho:g})")
weight_note = {
"gehan": "weights n(t), the number at risk", "tarone_ware": "weights √n(t)",
"peto_prentice": "weights S̃(t) = Π(1 − d/(n + 1)) (Peto's survival estimate)",
"modified_peto": "weights S̃(t)·n/(n + 1) (Andersen et al.)",
}.get(weights, f"weights S(t−)^ρ (1 − S(t−))^γ with ρ = {rho:g}, γ = {gamma:g}, from the pooled Kaplan–Meier curve" if gamma
else f"weights S(t−)^ρ with ρ = {rho:g} from the pooled Kaplan–Meier curve")
def lr_test(tt, ee, gg, ss):
"""survdiff's G-ρ family where it applies; the weighted twin for the other weights."""
if weights in ("logrank", "peto") or (weights == "fh" and gamma == 0):
return sv.logrank(tt, ee, gg, strata=ss, rho=rho)
return sa.logrank_weighted(tt, ee, gg, strata=ss, weights=weights, rho=rho, gamma=gamma)
if sname:
test_label += f", stratified by {sname},"
res = lr_test(t, ev, codes, scodes)
chisq, dof, p = res["chisq"], res["df"], res["p"]
values = {"chisq": chisq, "df": float(dof), "p": p, "n": float(len(t)), "events": float(ev.sum()), "n_groups": float(len(levels)),
"rho": rho, "gamma": gamma, "event_label": event_label, "test_label": test_label}
rows = []
for i, lv in enumerate(levels):
m = codes == i
values[f"n[{lv}]"], values[f"events[{lv}]"] = float(m.sum()), float(ev[m].sum())
values[f"obs[{lv}]"], values[f"exp[{lv}]"] = float(res["obs"][i]), float(res["exp"][i])
rows.append({"group": lv, "n": float(m.sum()), "events": float(ev[m].sum()), "obs": float(res["obs"][i]),
"exp": float(res["exp"][i]), "oe": float((res["obs"][i] - res["exp"][i]) ** 2 / res["exp"][i])})
# %% Pairwise comparisons
pair_rows = []
if True and len(levels) > 2:
pairs = list(combinations(range(len(levels)), 2))
raw = []
for a, b in pairs:
m = (codes == a) | (codes == b)
r = lr_test(t[m], ev[m], (codes[m] == b).astype(int), None if scodes is None else scodes[m])
raw.append((r["chisq"], r["p"]))
adj = p_adjust([x[1] for x in raw], "holm")
for (a, b), (c2, pr), pa in zip(pairs, raw, adj):
key = f"{levels[a]} vs {levels[b]}"
values[f"chisq_pair[{key}]"], values[f"p_pair[{key}]"], values[f"p_pair_adj[{key}]"] = c2, pr, float(pa)
pair_rows.append({"pair": key, "chisq": c2, "p": pr, "p_adj": float(pa)})
# %% Two-group alternatives: supremum, max-combo, restricted mean survival time
test_kind = "max_combo"
values.update({"logrank_p": p, "test_kind": test_kind, "renyi_q": None, "renyi_max_u": None, "renyi_var": None, "combo_max_z": None, "tau": None,
"rmst_diff": None, "rmst_diff_se": None, "rmst_diff_low": None, "rmst_diff_high": None, "rmst_z": None})
if test_kind != "chisq" and len(levels) != 2:
raise ValueError(f"This test compares exactly two groups; {g} has {len(levels)}")
extra_tables = []
statistics = [{"key": "chisq", "label": "χ²", "value": chisq}, {"key": "df", "label": "df", "value": float(dof), "format": "integer"}, {"key": "p", "label": "p", "value": p, "format": "p"}]
summary_text = f"{test_label} χ²({dof}) = {chisq:.2f}, {cs.fmt_p(p)}."
apa_text = f"χ²({dof}, N = {len(t)}) = {cs.fmt_num(chisq)}, {cs.fmt_p(p)}"
rmst_tau = None
if test_kind == "renyi":
rn = sa.renyi_test(t, ev, codes, scodes, weights=weights, rho=rho, gamma=gamma)
p = rn["p"]
test_label = "The Rényi supremum test" + (f", stratified by {sname}," if sname else "")
values.update({"p": p, "renyi_q": rn["q"], "renyi_max_u": rn["max_u"], "renyi_var": rn["var"], "test_label": test_label})
statistics = [{"key": "renyi_q", "label": "Q", "value": rn["q"]}, {"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "logrank_p", "label": "Log-rank p", "value": values["logrank_p"], "format": "p"}]
summary_text = f"{test_label.rstrip(',')}: Q = {rn['q']:.3f}, {cs.fmt_p(p)}."
apa_text = f"Q = {cs.fmt_num(rn['q'])}, {cs.fmt_p(p)}"
elif test_kind == "max_combo":
mc = sa.max_combo_test(t, ev, codes, scodes, reps=int(4999), seed=42)
p = mc["p"]
test_label = "The max-combo test" + (f", stratified by {sname}," if sname else "")
values.update({"p": p, "combo_max_z": mc["max_z"], "test_label": test_label})
combo_rows = []
for lab, zv in zip(mc["labels"], mc["z"]):
values[f"combo_z[{lab}]"] = float(zv)
combo_rows.append({"test": lab, "z": float(zv)})
extra_tables.append({"key": "combo", "title": "Fleming–Harrington components", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "z", "label": "Z", "type": "number"}], "rows": combo_rows,
"note": "FH(ρ, γ) weights S(t−)^ρ (1 − S(t−))^γ. The p-value allows for taking the largest of the four."})
statistics = [{"key": "combo_max_z", "label": "Largest |Z|", "value": mc["max_z"]}, {"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "logrank_p", "label": "Log-rank p", "value": values["logrank_p"], "format": "p"}]
summary_text = f"{test_label.rstrip(',')}: largest |Z| = {mc['max_z']:.3f}, {cs.fmt_p(p)}."
apa_text = f"max |Z| = {cs.fmt_num(mc['max_z'])}, {cs.fmt_p(p)}"
elif test_kind == "rmst":
if sname:
raise ValueError("The restricted mean survival difference does not take strata")
rmst_tau = min(float(t[codes == i].max()) for i in range(2)) # horizon
rms = []
rm_rows = []
for i, lv in enumerate(levels):
m = codes == i
fit_i = sv.km(t[m], ev[m], conf=0.95, conf_type="log-log")
val_i, se_i = sv.rmst(fit_i, rmst_tau)
rms.append((val_i, se_i))
values[f"rmst[{lv}]"], values[f"rmst_se[{lv}]"] = val_i, se_i
rm_rows.append({"group": lv, "rmst": val_i, "se": se_i})
diff = rms[1][0] - rms[0][0]
se_d = float(np.hypot(rms[0][1], rms[1][1]))
zv = diff / se_d
p = float(2 * stats.norm.sf(abs(zv)))
q_ = float(stats.norm.ppf(0.975))
test_label = "The restricted mean survival time comparison"
values.update({"p": p, "tau": rmst_tau, "rmst_diff": diff, "rmst_diff_se": se_d, "rmst_diff_low": diff - q_ * se_d, "rmst_diff_high": diff + q_ * se_d, "rmst_z": zv, "test_label": test_label})
extra_tables.append({"key": "rmst", "title": f"Restricted mean survival time up to {rmst_tau:g}", "columns": [
{"key": "group", "label": g, "type": "string"}, {"key": "rmst", "label": "RMST", "type": "number"}, {"key": "se", "label": "SE", "type": "number"}], "rows": rm_rows,
"note": f"{levels[1]} minus {levels[0]} = {diff:.4g}, 95% CI [{diff - q_ * se_d:.4g}, {diff + q_ * se_d:.4g}]."})
statistics = [{"key": "rmst_diff", "label": "RMST difference", "value": diff}, {"key": "tau", "label": "Horizon τ", "value": rmst_tau},
{"key": "p", "label": "p", "value": p, "format": "p"}, {"key": "logrank_p", "label": "Log-rank p", "value": values["logrank_p"], "format": "p"}]
summary_text = f"Up to {rmst_tau:g}, mean event-free time differed by {diff:.3g} ({levels[1]} minus {levels[0]}), {cs.fmt_p(p)}."
apa_text = f"RMST difference = {cs.fmt_num(diff)}, 95% CI [{cs.fmt_num(diff - q_ * se_d)}, {cs.fmt_num(diff + q_ * se_d)}], {cs.fmt_p(p)}"
short_title = test_label.removeprefix("The ").rstrip(",")
method_note = {
"rmst": "Each restricted mean is the area under that group's Kaplan–Meier curve up to τ",
"max_combo": "The four tests take their weights from the pooled Kaplan–Meier curve",
}.get(test_kind, f"Test {weight_note}")
# %% Assumptions — Grambsch–Therneau test on a Cox model of the groups
X = np.column_stack([(codes == i).astype(float) for i in range(1, len(levels))])
cox = sv.cox_fit(t, ev, X, strata=scodes, ties="efron")
one_time = np.unique(t[ev]).size < 2 # with every event at one time the proportional-hazards test is undefined
if one_time:
warnings.append(cs.cs_warning("CS_W_TIES", column=tcol, consequence="every event happened at the same time, so the proportional-hazards test is not computed."))
ph_chisq, ph_p = None, None
ph_check = {"key": "proportional_hazards", "label": "Proportional hazards", "status": "info", "detail": "Not tested: every event happened at the same time."}
else:
zph = sv.cox_zph(t, ev, X, cox["coef"], [list(range(X.shape[1]))], strata=scodes, ties="efron")
ph_chisq, _, ph_p = zph["global"]
ph_check = {
"key": "proportional_hazards", "label": "Proportional hazards",
"status": "warn" if ph_p < 0.05 else "pass", "statistic": ph_chisq, "p": ph_p,
"detail": (f"Grambsch–Therneau test χ²({X.shape[1]}) = {ph_chisq:.2f}, {cs.fmt_p(ph_p)}: "
+ ("hazard ratios change over time; the log-rank test loses power when curves cross." if ph_p < 0.05 else "no evidence that hazard ratios change over time.")),
}
values["ph_chisq"], values["ph_p"] = ph_chisq, ph_p
assumptions = [ph_check, {"key": "censoring", "label": "Non-informative censoring", "status": "info",
"detail": f"{int((~ev).sum())} of {len(ev)} observations are censored."}]
low = [r["group"] for r in rows if r["events"] < 5]
assumptions.append({"key": "sample_size", "label": "Number of events", "status": "warn" if low else "pass",
"detail": f"Fewer than 5 events in {', '.join(low)}." if low else "At least 5 events per group."})
# %% Kaplan–Meier curves for the chart
curve = {"time": [], "surv": [], "low": [], "high": [], "strata": [], "nrisk": [], "ncensor": []}
for i, lv in enumerate(levels):
m = codes == i
fit = sv.km(t[m], ev[m], conf=0.95, conf_type="log-log")
nan = lambda x: None if not np.isfinite(x) else float(x) # noqa: E731
curve["time"] += [0.0] + fit["time"].tolist()
curve["surv"] += [1.0] + fit["surv"].tolist()
curve["low"] += [1.0] + [nan(x) for x in fit["lower"]]
curve["high"] += [1.0] + [nan(x) for x in fit["upper"]]
curve["strata"] += [lv] * (len(fit["time"]) + 1)
curve["nrisk"] += [float(m.sum())] + fit["n_risk"].tolist()
curve["ncensor"] += [0.0] + fit["n_censor"].tolist()
# %% Result
tables = [{"key": "groups", "title": "Observed and expected events", "columns": [
{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "events", "label": "Events", "type": "integer"}, {"key": "obs", "label": "Observed (weighted)", "type": "number"},
{"key": "exp", "label": "Expected (weighted)", "type": "number"}, {"key": "oe", "label": "(O−E)²/E", "type": "number"},
], "rows": rows}] + extra_tables
if pair_rows:
tables.append({"key": "posthoc", "title": "Pairwise comparisons", "columns": [
{"key": "pair", "label": "Pair", "type": "string"}, {"key": "chisq", "label": "χ²", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}, {"key": "p_adj", "label": "p (adjusted)", "type": "pvalue"},
], "rows": pair_rows, "note": "Adjustment: holm."})
cs.publish({
"method": "survival.logrank",
"methodVersion": "1.2.1",
"title": short_title[:1].upper() + short_title[1:] + f" by {g}",
"engine": cs.engine_info("numpy", "scipy", "statsmodels", "codesplash"),
"n": int(len(t)),
"summary": summary_text,
"apa": apa_text,
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {event_label}. {method_note}" + (f" within strata of {sname}." if sname else ".")],
"charts": [cs.chart("km", "km-curve", f"Kaplan–Meier curves by {g}", {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"low": cs.col("lower", curve["low"], "numeric"), "high": cs.col("upper", curve["high"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels),
"nrisk": cs.col("At risk", curve["nrisk"], "numeric"), "ncensor": cs.col("Censored", curve["ncensor"], "numeric"),
}), cs.chart("loglog", "loglog-survival", f"Log–log survival by {g}", {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels),
})] + ([cs.chart("rmst", "rmst-area", f"Restricted mean survival up to {rmst_tau:g}", {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels),
}, controls={"tau": rmst_tau})] if rmst_tau is not None else []),
"values": values,
})
Find it under Compare by in the setup, with exactly two groups.
An effect you can say out loud
In the appThe tests above give p-values only. A restricted meanRestricted mean survival timeThe average event-free time up to a horizon τ, the area under the survival curve; a difference in RMST is a difference in time. difference gives a size, and it stays meaningful when hazards cross.
Over the first 500 days, women lived 82 days longer than men on average (95% interval 39 to 125, p < .001).
RMST difference = 82.15, 95% CI [38.84, 125.46], p < .001
- RMST difference
- 82.148
- Horizon τ
- 500
- p
- < .001
- Log-rank p
- .001
Plots
View data
| upper | lower | Censored | At risk | sex | Survival probability | time |
|---|---|---|---|---|---|---|
| 1 | 1 | 0 | 138 | male | 1 | 0 |
| 0.9929 | 0.9341 | 0 | 138 | male | 0.9783 | 11 |
| 0.9890 | 0.9246 | 0 | 135 | male | 0.9710 | 12 |
| 0.9802 | 0.9058 | 0 | 134 | male | 0.9565 | 13 |
| 0.9755 | 0.8965 | 0 | 132 | male | 0.9493 | 15 |
| 0.9706 | 0.8874 | 0 | 131 | male | 0.9420 | 26 |
| 0.9655 | 0.8784 | 0 | 130 | male | 0.9348 | 30 |
| 0.9603 | 0.8695 | 0 | 129 | male | 0.9275 | 31 |
| 0.9497 | 0.8520 | 0 | 128 | male | 0.9130 | 53 |
| 0.9442 | 0.8433 | 0 | 126 | male | 0.9058 | 54 |
| 0.9386 | 0.8347 | 0 | 125 | male | 0.8986 | 59 |
| 0.9330 | 0.8262 | 0 | 124 | male | 0.8913 | 60 |
| 0.9216 | 0.8093 | 0 | 123 | male | 0.8768 | 65 |
| 0.9157 | 0.8010 | 0 | 121 | male | 0.8696 | 71 |
| 0.9099 | 0.7927 | 0 | 120 | male | 0.8623 | 81 |
| 0.8980 | 0.7762 | 0 | 119 | male | 0.8478 | 88 |
| 0.8920 | 0.7681 | 0 | 117 | male | 0.8406 | 92 |
| 0.8860 | 0.7599 | 0 | 116 | male | 0.8333 | 93 |
| 0.8799 | 0.7519 | 0 | 115 | male | 0.8261 | 95 |
| 0.8737 | 0.7438 | 0 | 114 | male | 0.8188 | 105 |
| 0.8676 | 0.7358 | 0 | 113 | male | 0.8116 | 107 |
| 0.8614 | 0.7278 | 0 | 112 | male | 0.8043 | 110 |
| 0.8552 | 0.7199 | 0 | 111 | male | 0.7971 | 116 |
| 0.8489 | 0.7119 | 0 | 110 | male | 0.7899 | 118 |
| 0.8426 | 0.7041 | 0 | 109 | male | 0.7826 | 131 |
| 0.8300 | 0.6884 | 0 | 108 | male | 0.7681 | 132 |
| 0.8236 | 0.6806 | 0 | 106 | male | 0.7609 | 135 |
| 0.8172 | 0.6728 | 0 | 105 | male | 0.7536 | 142 |
| 0.8108 | 0.6650 | 0 | 104 | male | 0.7464 | 144 |
| 0.8043 | 0.6573 | 0 | 103 | male | 0.7391 | 147 |
| 0.7913 | 0.6419 | 0 | 102 | male | 0.7246 | 156 |
| 0.7717 | 0.6191 | 0 | 100 | male | 0.7029 | 163 |
| 0.7651 | 0.6115 | 0 | 97 | male | 0.6957 | 166 |
| 0.7585 | 0.6039 | 0 | 96 | male | 0.6884 | 170 |
| 0.7585 | 0.6039 | 1 | 95 | male | 0.6884 | 174 |
| 0.7518 | 0.5963 | 0 | 94 | male | 0.6811 | 175 |
| 0.7451 | 0.5887 | 0 | 93 | male | 0.6738 | 176 |
| 0.7383 | 0.5811 | 0 | 92 | male | 0.6664 | 177 |
| 0.7248 | 0.5659 | 0 | 91 | male | 0.6518 | 179 |
| 0.7180 | 0.5584 | 0 | 89 | male | 0.6445 | 180 |
| 0.7044 | 0.5434 | 0 | 88 | male | 0.6298 | 181 |
| 0.6975 | 0.5359 | 0 | 86 | male | 0.6225 | 183 |
| 0.6975 | 0.5359 | 1 | 85 | male | 0.6225 | 185 |
| 0.6975 | 0.5359 | 1 | 84 | male | 0.6225 | 188 |
| 0.6905 | 0.5283 | 0 | 83 | male | 0.6150 | 189 |
| 0.6905 | 0.5283 | 1 | 82 | male | 0.6150 | 191 |
| 0.6905 | 0.5283 | 1 | 81 | male | 0.6150 | 196 |
| 0.6833 | 0.5204 | 1 | 80 | male | 0.6073 | 197 |
| 0.6760 | 0.5124 | 0 | 78 | male | 0.5995 | 202 |
| 0.6687 | 0.5045 | 0 | 77 | male | 0.5917 | 207 |
| 0.6614 | 0.4966 | 0 | 76 | male | 0.5839 | 210 |
| 0.6541 | 0.4887 | 0 | 75 | male | 0.5762 | 212 |
| 0.6467 | 0.4808 | 0 | 74 | male | 0.5684 | 218 |
| 0.6467 | 0.4808 | 1 | 73 | male | 0.5684 | 221 |
| 0.6392 | 0.4728 | 1 | 72 | male | 0.5605 | 222 |
| 0.6316 | 0.4648 | 0 | 70 | male | 0.5525 | 223 |
| 0.6316 | 0.4648 | 2 | 69 | male | 0.5525 | 225 |
| 0.6238 | 0.4564 | 0 | 67 | male | 0.5442 | 229 |
| 0.6160 | 0.4481 | 0 | 66 | male | 0.5360 | 230 |
| 0.6160 | 0.4481 | 1 | 65 | male | 0.5360 | 237 |
First 60 of 208 rows.
View data
| sex | Survival probability | time |
|---|---|---|
| male | 1 | 0 |
| male | 0.9783 | 11 |
| male | 0.9710 | 12 |
| male | 0.9565 | 13 |
| male | 0.9493 | 15 |
| male | 0.9420 | 26 |
| male | 0.9348 | 30 |
| male | 0.9275 | 31 |
| male | 0.9130 | 53 |
| male | 0.9058 | 54 |
| male | 0.8986 | 59 |
| male | 0.8913 | 60 |
| male | 0.8768 | 65 |
| male | 0.8696 | 71 |
| male | 0.8623 | 81 |
| male | 0.8478 | 88 |
| male | 0.8406 | 92 |
| male | 0.8333 | 93 |
| male | 0.8261 | 95 |
| male | 0.8188 | 105 |
| male | 0.8116 | 107 |
| male | 0.8043 | 110 |
| male | 0.7971 | 116 |
| male | 0.7899 | 118 |
| male | 0.7826 | 131 |
| male | 0.7681 | 132 |
| male | 0.7609 | 135 |
| male | 0.7536 | 142 |
| male | 0.7464 | 144 |
| male | 0.7391 | 147 |
| male | 0.7246 | 156 |
| male | 0.7029 | 163 |
| male | 0.6957 | 166 |
| male | 0.6884 | 170 |
| male | 0.6884 | 174 |
| male | 0.6811 | 175 |
| male | 0.6738 | 176 |
| male | 0.6664 | 177 |
| male | 0.6518 | 179 |
| male | 0.6445 | 180 |
| male | 0.6298 | 181 |
| male | 0.6225 | 183 |
| male | 0.6225 | 185 |
| male | 0.6225 | 188 |
| male | 0.6150 | 189 |
| male | 0.6150 | 191 |
| male | 0.6150 | 196 |
| male | 0.6073 | 197 |
| male | 0.5995 | 202 |
| male | 0.5917 | 207 |
| male | 0.5839 | 210 |
| male | 0.5762 | 212 |
| male | 0.5684 | 218 |
| male | 0.5684 | 221 |
| male | 0.5605 | 222 |
| male | 0.5525 | 223 |
| male | 0.5525 | 225 |
| male | 0.5442 | 229 |
| male | 0.5360 | 230 |
| male | 0.5360 | 237 |
First 60 of 208 rows.
View data
| sex | Survival probability | time |
|---|---|---|
| male | 1 | 0 |
| male | 0.9783 | 11 |
| male | 0.9710 | 12 |
| male | 0.9565 | 13 |
| male | 0.9493 | 15 |
| male | 0.9420 | 26 |
| male | 0.9348 | 30 |
| male | 0.9275 | 31 |
| male | 0.9130 | 53 |
| male | 0.9058 | 54 |
| male | 0.8986 | 59 |
| male | 0.8913 | 60 |
| male | 0.8768 | 65 |
| male | 0.8696 | 71 |
| male | 0.8623 | 81 |
| male | 0.8478 | 88 |
| male | 0.8406 | 92 |
| male | 0.8333 | 93 |
| male | 0.8261 | 95 |
| male | 0.8188 | 105 |
| male | 0.8116 | 107 |
| male | 0.8043 | 110 |
| male | 0.7971 | 116 |
| male | 0.7899 | 118 |
| male | 0.7826 | 131 |
| male | 0.7681 | 132 |
| male | 0.7609 | 135 |
| male | 0.7536 | 142 |
| male | 0.7464 | 144 |
| male | 0.7391 | 147 |
| male | 0.7246 | 156 |
| male | 0.7029 | 163 |
| male | 0.6957 | 166 |
| male | 0.6884 | 170 |
| male | 0.6884 | 174 |
| male | 0.6811 | 175 |
| male | 0.6738 | 176 |
| male | 0.6664 | 177 |
| male | 0.6518 | 179 |
| male | 0.6445 | 180 |
| male | 0.6298 | 181 |
| male | 0.6225 | 183 |
| male | 0.6225 | 185 |
| male | 0.6225 | 188 |
| male | 0.6150 | 189 |
| male | 0.6150 | 191 |
| male | 0.6150 | 196 |
| male | 0.6073 | 197 |
| male | 0.5995 | 202 |
| male | 0.5917 | 207 |
| male | 0.5839 | 210 |
| male | 0.5762 | 212 |
| male | 0.5684 | 218 |
| male | 0.5684 | 221 |
| male | 0.5605 | 222 |
| male | 0.5525 | 223 |
| male | 0.5525 | 225 |
| male | 0.5442 | 229 |
| male | 0.5360 | 230 |
| male | 0.5360 | 237 |
First 60 of 208 rows.
Assumptions
- Proportional hazards — Grambsch–Therneau test χ²(1) = 2.86, p = .091: no evidence that hazard ratios change over time.
- Non-informative censoring — 63 of 228 observations are censored.
- Number of events — At least 5 events per group.
Observed and expected events
| sex | n | Events | Observed (weighted) | Expected (weighted) | (O−E)²/E |
|---|---|---|---|---|---|
| male | 138 | 112 | 112 | 91.582 | 4.552 |
| female | 90 | 53 | 53 | 73.418 | 5.678 |
Restricted mean survival time up to 500
| sex | RMST | SE |
|---|---|---|
| male | 278.76 | 14.355 |
| female | 360.91 | 16.801 |
female minus male = 82.15, 95% CI [38.84, 125.5].
- Event: dead = true. Each restricted mean is the area under that group's Kaplan–Meier curve up to τ.
The exact R script · R R version 4.5.1 (2025-06-13)
# Log-rank test (compare survival curves)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.logrank 1.2.1 · spec 8e568348966956f6
# Dataset: lung (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(survival)
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/lung.parquet", col_select = c("time", "dead", "sex")))
n_input <- nrow(df)
df[["dead"]] <- factor(df[["dead"]], levels = c("false", "true")) # stored level order
df[["sex"]] <- factor(df[["sex"]], levels = c("male", "female")) # stored level order
df <- df[stats::complete.cases(df[c("time", "dead", "sex")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("time", "dead", "sex")) # infinite values stop the run (registry/errors.yaml)
# %% Event coding
tcol <- "time"
ecol <- "dead"
tt <- as.numeric(df[[tcol]])
if (any(tt < 0)) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = "zero or positive (survival times)", count = sum(tt < 0))
event_level <- "true" # the event; other levels are censored
ev <- as.character(df[[ecol]]) == event_level
event_label <- sprintf("%s = %s", ecol, event_level)
if (!any(ev)) cs_error("CS_E_NO_EVENTS", event = event_label)
# %% Log-rank test
g <- "sex"
levels_g <- levels(df[[g]])
if (length(levels_g) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = length(levels_g))
gv <- factor(as.character(df[[g]]), levels = levels_g)
sname <- NULL
sv <- NULL
weights <- "logrank"
rho <- switch(weights, logrank = 0, peto = 1, fh = 0.5, 0) # survdiff(rho = …)
gamma <- if (weights == "fh") 0 else 0 # Fleming–Harrington (1 − S(t−))^γ; survdiff has γ = 0 only
use_survdiff <- weights %in% c("logrank", "peto") || (weights == "fh" && gamma == 0)
weight_note <- switch(weights,
gehan = "weights n(t), the number at risk", tarone_ware = "weights √n(t)",
peto_prentice = "weights S̃(t) = Π(1 − d/(n + 1)) (Peto's survival estimate)",
modified_peto = "weights S̃(t)·n/(n + 1) (Andersen et al.)",
if (gamma != 0) sprintf("weights S(t−)^ρ (1 − S(t−))^γ with ρ = %s, γ = %s, from the pooled Kaplan–Meier curve", format(rho), format(gamma))
else sprintf("weights S(t−)^ρ with ρ = %s from the pooled Kaplan–Meier curve", format(rho)))
lr_test <- function(tt, ee, gg, ss) {
# survdiff where it applies; codesplashr's weighted log-rank for Gehan, Tarone–Ware, Peto–Prentice and FH(ρ, γ)
if (use_survdiff) {
r <- if (is.null(ss)) survdiff(Surv(tt, ee) ~ gg, rho = rho) else survdiff(Surv(tt, ee) ~ gg + strata(ss), rho = rho)
list(obs = if (is.matrix(r$obs)) rowSums(r$obs) else r$obs, exp = if (is.matrix(r$exp)) rowSums(r$exp) else r$exp, chisq = r$chisq)
} else {
cs_surv_logrank(tt, ee, gg, ss, weights = weights, rho = rho, gamma = gamma)
}
}
test_label <- switch(weights, logrank = "The log-rank test", peto = "The Peto–Peto weighted log-rank test (ρ = 1)",
gehan = "The Gehan–Breslow (generalized Wilcoxon) test", tarone_ware = "The Tarone–Ware test",
peto_prentice = "The Peto–Prentice test", modified_peto = "The modified Peto–Peto (Andersen) test",
if (gamma != 0) sprintf("The Fleming–Harrington G(ρ = %s, γ = %s) test", format(rho), format(gamma))
else sprintf("The Fleming–Harrington G-ρ test (ρ = %s)", format(rho)))
if (!is.null(sname)) test_label <- sprintf("%s, stratified by %s,", test_label, sname)
lr <- lr_test(tt, ev, gv, sv)
obs <- lr$obs
expd <- lr$exp
chisq <- lr$chisq
dof <- length(levels_g) - 1
p <- stats::pchisq(chisq, dof, lower.tail = FALSE)
values <- list(chisq = chisq, df = dof, p = p, n = length(tt), events = sum(ev), n_groups = length(levels_g), rho = rho, gamma = gamma,
event_label = event_label, test_label = test_label)
rows <- list()
for (i in seq_along(levels_g)) {
lv <- levels_g[i]
m <- gv == lv
values[[sprintf("n[%s]", lv)]] <- sum(m)
values[[sprintf("events[%s]", lv)]] <- sum(ev[m])
values[[sprintf("obs[%s]", lv)]] <- unname(obs[i])
values[[sprintf("exp[%s]", lv)]] <- unname(expd[i])
rows[[i]] <- list(group = lv, n = sum(m), events = sum(ev[m]), obs = unname(obs[i]), exp = unname(expd[i]),
oe = unname((obs[i] - expd[i])^2 / expd[i]))
}
# %% Pairwise comparisons
pair_rows <- list()
if (TRUE && length(levels_g) > 2) {
pairs <- utils::combn(length(levels_g), 2, simplify = FALSE)
raw <- lapply(pairs, function(ab) {
m <- gv %in% levels_g[ab]
gg <- factor(as.character(gv[m]), levels = levels_g[ab])
r <- lr_test(tt[m], ev[m], gg, if (is.null(sv)) NULL else sv[m])
c(r$chisq, stats::pchisq(r$chisq, 1, lower.tail = FALSE))
})
adj <- cs_p_adjust(vapply(raw, `[`, numeric(1), 2), "holm")
for (i in seq_along(pairs)) {
key <- sprintf("%s vs %s", levels_g[pairs[[i]][1]], levels_g[pairs[[i]][2]])
values[[sprintf("chisq_pair[%s]", key)]] <- raw[[i]][1]
values[[sprintf("p_pair[%s]", key)]] <- raw[[i]][2]
values[[sprintf("p_pair_adj[%s]", key)]] <- adj[i]
pair_rows[[i]] <- list(pair = key, chisq = raw[[i]][1], p = raw[[i]][2], p_adj = adj[i])
}
}
# %% Two-group alternatives: supremum, max-combo, restricted mean survival time
test_kind <- "rmst"
values[c("logrank_p", "test_kind", "renyi_q", "renyi_max_u", "renyi_var", "combo_max_z", "tau", "rmst_diff", "rmst_diff_se", "rmst_diff_low", "rmst_diff_high", "rmst_z")] <-
list(p, test_kind, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)
if (test_kind != "chisq" && length(levels_g) != 2) stop(sprintf("This test compares exactly two groups; %s has %d", g, length(levels_g)))
extra_tables <- list()
statistics <- list(list(key = "chisq", label = "χ²", value = chisq), list(key = "df", label = "df", value = dof, format = "integer"), list(key = "p", label = "p", value = p, format = "p"))
summary_text <- sprintf("%s χ²(%d) = %.2f, %s.", test_label, dof, chisq, cs_fmt_p(p))
apa_text <- sprintf("χ²(%d, N = %d) = %s, %s", dof, length(tt), cs_fmt_num(chisq), cs_fmt_p(p))
rmst_tau <- NULL
if (test_kind == "renyi") {
rn <- cs_surv_renyi(tt, ev, gv, sv, weights = weights, rho = rho, gamma = gamma)
p <- rn$p
test_label <- paste0("The Rényi supremum test", if (!is.null(sname)) sprintf(", stratified by %s,", sname) else "")
values$p <- p
values$renyi_q <- rn$q
values$renyi_max_u <- rn$max_u
values$renyi_var <- rn$var
values$test_label <- test_label
statistics <- list(list(key = "renyi_q", label = "Q", value = rn$q), list(key = "p", label = "p", value = p, format = "p"),
list(key = "logrank_p", label = "Log-rank p", value = values$logrank_p, format = "p"))
summary_text <- sprintf("%s: Q = %.3f, %s.", sub(",$", "", test_label), rn$q, cs_fmt_p(p))
apa_text <- sprintf("Q = %s, %s", cs_fmt_num(rn$q), cs_fmt_p(p))
} else if (test_kind == "max_combo") {
mc <- cs_surv_max_combo(tt, ev, gv, sv, reps = as.integer(19999), seed = 42)
p <- mc$p
test_label <- paste0("The max-combo test", if (!is.null(sname)) sprintf(", stratified by %s,", sname) else "")
values$p <- p
values$combo_max_z <- mc$max_z
values$test_label <- test_label
combo_rows <- list()
for (i in seq_along(mc$labels)) {
values[[sprintf("combo_z[%s]", mc$labels[i])]] <- mc$z[i]
combo_rows[[i]] <- list(test = mc$labels[i], z = mc$z[i])
}
extra_tables[[1]] <- list(key = "combo", title = "Fleming–Harrington components", columns = list(
list(key = "test", label = "Test", type = "string"), list(key = "z", label = "Z", type = "number")), rows = combo_rows,
note = "FH(ρ, γ) weights S(t−)^ρ (1 − S(t−))^γ. The p-value allows for taking the largest of the four.")
statistics <- list(list(key = "combo_max_z", label = "Largest |Z|", value = mc$max_z), list(key = "p", label = "p", value = p, format = "p"),
list(key = "logrank_p", label = "Log-rank p", value = values$logrank_p, format = "p"))
summary_text <- sprintf("%s: largest |Z| = %.3f, %s.", sub(",$", "", test_label), mc$max_z, cs_fmt_p(p))
apa_text <- sprintf("max |Z| = %s, %s", cs_fmt_num(mc$max_z), cs_fmt_p(p))
} else if (test_kind == "rmst") {
if (!is.null(sname)) stop("The restricted mean survival difference does not take strata")
rmst_tau <- 500 # horizon
rms <- list()
rm_rows <- list()
for (i in seq_along(levels_g)) {
lv <- levels_g[i]
m <- gv == lv
tb <- summary(survfit(Surv(tt[m], ev[m]) ~ 1), rmean = rmst_tau)$table
rms[[i]] <- c(unname(tb[["rmean"]]), unname(tb[["se(rmean)"]]))
values[[sprintf("rmst[%s]", lv)]] <- rms[[i]][1]
values[[sprintf("rmst_se[%s]", lv)]] <- rms[[i]][2]
rm_rows[[i]] <- list(group = lv, rmst = rms[[i]][1], se = rms[[i]][2])
}
diff_r <- rms[[2]][1] - rms[[1]][1]
se_d <- sqrt(rms[[1]][2]^2 + rms[[2]][2]^2)
zv <- diff_r / se_d
p <- 2 * stats::pnorm(abs(zv), lower.tail = FALSE)
q_ <- stats::qnorm(0.975)
test_label <- "The restricted mean survival time comparison"
values$p <- p
values$tau <- rmst_tau
values$rmst_diff <- diff_r
values$rmst_diff_se <- se_d
values$rmst_diff_low <- diff_r - q_ * se_d
values$rmst_diff_high <- diff_r + q_ * se_d
values$rmst_z <- zv
values$test_label <- test_label
extra_tables[[1]] <- list(key = "rmst", title = sprintf("Restricted mean survival time up to %g", rmst_tau), columns = list(
list(key = "group", label = g, type = "string"), list(key = "rmst", label = "RMST", type = "number"), list(key = "se", label = "SE", type = "number")), rows = rm_rows,
note = sprintf("%s minus %s = %.4g, 95%% CI [%.4g, %.4g].", levels_g[2], levels_g[1], diff_r, diff_r - q_ * se_d, diff_r + q_ * se_d))
statistics <- list(list(key = "rmst_diff", label = "RMST difference", value = diff_r), list(key = "tau", label = "Horizon τ", value = rmst_tau),
list(key = "p", label = "p", value = p, format = "p"), list(key = "logrank_p", label = "Log-rank p", value = values$logrank_p, format = "p"))
summary_text <- sprintf("Up to %g, mean event-free time differed by %.3g (%s minus %s), %s.", rmst_tau, diff_r, levels_g[2], levels_g[1], cs_fmt_p(p))
apa_text <- sprintf("RMST difference = %s, 95%% CI [%s, %s], %s", cs_fmt_num(diff_r), cs_fmt_num(diff_r - q_ * se_d), cs_fmt_num(diff_r + q_ * se_d), cs_fmt_p(p))
}
short_title <- sub(",$", "", sub("^The ", "", test_label))
method_note <- switch(test_kind,
rmst = "Each restricted mean is the area under that group's Kaplan–Meier curve up to τ",
max_combo = "The four tests take their weights from the pooled Kaplan–Meier curve",
paste("Test", weight_note))
# %% Assumptions — Grambsch–Therneau test on a Cox model of the groups
ctl <- coxph.control(eps = 1e-12, toler.chol = 1e-15, iter.max = 60)
cox <- if (is.null(sv)) coxph(Surv(tt, ev) ~ gv, ties = "efron", control = ctl) else
coxph(Surv(tt, ev) ~ gv + strata(sv), ties = "efron", control = ctl)
one_time <- length(unique(tt[ev])) < 2 # with every event at one time the proportional-hazards test is undefined
if (one_time) {
warnings <- c(warnings, cs_warning("CS_W_TIES", column = tcol, consequence = "every event happened at the same time, so the proportional-hazards test is not computed."))
ph_chisq <- NA_real_
ph_p <- NA_real_
ph_check <- list(key = "proportional_hazards", label = "Proportional hazards", status = "info", detail = "Not tested: every event happened at the same time.")
} else {
zt <- cox.zph(cox, transform = "km")$table
ph_chisq <- unname(zt["GLOBAL", "chisq"])
ph_p <- unname(zt["GLOBAL", "p"])
ph_check <- list(key = "proportional_hazards", label = "Proportional hazards", status = if (ph_p < 0.05) "warn" else "pass",
statistic = ph_chisq, p = ph_p,
detail = paste0(sprintf("Grambsch–Therneau test χ²(%d) = %.2f, %s: ", dof, ph_chisq, cs_fmt_p(ph_p)),
if (ph_p < 0.05) "hazard ratios change over time; the log-rank test loses power when curves cross."
else "no evidence that hazard ratios change over time."))
}
values$ph_chisq <- ph_chisq
values$ph_p <- ph_p
assumptions <- list(
ph_check,
list(key = "censoring", label = "Non-informative censoring", status = "info",
detail = sprintf("%d of %d observations are censored.", sum(!ev), length(ev)))
)
low <- levels_g[vapply(rows, function(r) r$events < 5, logical(1))]
assumptions[[3]] <- list(key = "sample_size", label = "Number of events", status = if (length(low)) "warn" else "pass",
detail = if (length(low)) sprintf("Fewer than 5 events in %s.", paste(low, collapse = ", ")) else "At least 5 events per group.")
# %% Kaplan–Meier curves for the chart
curve <- list(time = numeric(0), surv = numeric(0), low = numeric(0), high = numeric(0), strata = character(0),
nrisk = numeric(0), ncensor = numeric(0))
for (lv in levels_g) {
m <- gv == lv
fit <- survfit(Surv(tt[m], ev[m]) ~ 1, conf.type = "log-log")
curve$time <- c(curve$time, 0, fit$time)
curve$surv <- c(curve$surv, 1, fit$surv)
curve$low <- c(curve$low, 1, fit$lower)
curve$high <- c(curve$high, 1, fit$upper)
curve$strata <- c(curve$strata, rep(lv, length(fit$time) + 1))
curve$nrisk <- c(curve$nrisk, sum(m), fit$n.risk)
curve$ncensor <- c(curve$ncensor, 0, fit$n.censor)
}
# %% Result
tables <- list(list(key = "groups", title = "Observed and expected events", columns = list(
list(key = "group", label = g, type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "events", label = "Events", type = "integer"), list(key = "obs", label = "Observed (weighted)", type = "number"),
list(key = "exp", label = "Expected (weighted)", type = "number"), list(key = "oe", label = "(O−E)²/E", type = "number")
), rows = rows))
tables <- c(tables, extra_tables)
if (length(pair_rows)) {
tables[[length(tables) + 1]] <- list(key = "posthoc", title = "Pairwise comparisons", columns = list(
list(key = "pair", label = "Pair", type = "string"), list(key = "chisq", label = "χ²", type = "number"),
list(key = "p", label = "p", type = "pvalue"), list(key = "p_adj", label = "p (adjusted)", type = "pvalue")
), rows = pair_rows, note = "Adjustment: holm.")
}
cs_publish(list(
method = "survival.logrank",
methodVersion = "1.2.1",
title = paste(paste0(toupper(substr(short_title, 1, 1)), substr(short_title, 2, nchar(short_title))), "by", g),
engine = cs_engine_info("survival", "codesplashr"),
n = length(tt),
summary = summary_text,
apa = apa_text,
statistics = statistics,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Event: %s. %s%s", event_label, method_note,
if (is.null(sname)) "." else sprintf(" within strata of %s.", sname))),
charts = c(list(cs_chart("km", "km-curve", paste("Kaplan–Meier curves by", g), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
low = cs_col("lower", curve$low, "numeric"), high = cs_col("upper", curve$high, "numeric"),
strata = cs_col(g, curve$strata, "categorical", levels = levels_g),
nrisk = cs_col("At risk", curve$nrisk, "numeric"), ncensor = cs_col("Censored", curve$ncensor, "numeric")
)), cs_chart("loglog", "loglog-survival", paste("Log–log survival by", g), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
strata = cs_col(g, curve$strata, "categorical", levels = levels_g)
))), if (!is.null(rmst_tau)) list(cs_chart("rmst", "rmst-area", sprintf("Restricted mean survival up to %g", rmst_tau), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
strata = cs_col(g, curve$strata, "categorical", levels = levels_g)
), controls = list(tau = rmst_tau)))),
values = values
))
RMST difference = 82.15, 95% CI [38.84, 125.46], p < .001
- RMST difference
- 82.148
- Horizon τ
- 500
- p
- < .001
- Log-rank p
- .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Proportional hazards — Grambsch–Therneau test χ²(1) = 2.86, p = .091: no evidence that hazard ratios change over time.
- Non-informative censoring — 63 of 228 observations are censored.
- Number of events — At least 5 events per group.
Observed and expected events
| sex | n | Events | Observed (weighted) | Expected (weighted) | (O−E)²/E |
|---|---|---|---|---|---|
| male | 138 | 112 | 112 | 91.582 | 4.552 |
| female | 90 | 53 | 53 | 73.418 | 5.678 |
Restricted mean survival time up to 500
| sex | RMST | SE |
|---|---|---|
| male | 278.76 | 14.355 |
| female | 360.91 | 16.801 |
female minus male = 82.15, 95% CI [38.84, 125.5].
- Event: dead = true. Each restricted mean is the area under that group's Kaplan–Meier curve up to τ.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Log-rank test (compare survival curves)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.logrank 1.2.1 · spec 8e568348966956f6
# Dataset: lung (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
from itertools import combinations
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import survival as sv # survdiff / cox.zph twins
from codesplash.stats import survival_adv as sa # other weights (Gehan, Tarone–Ware, Peto–Prentice, FH(ρ, γ))
from codesplash.stats.padjust import p_adjust
# %% Data
df = pd.read_parquet("tests/parity/fixtures/lung.parquet", columns=["time", "dead", "sex"])
n_input = len(df)
df["dead"] = pd.Categorical(df["dead"], categories=["false", "true"]) # stored level order
df["sex"] = pd.Categorical(df["sex"], categories=["male", "female"]) # stored level order
df = df.dropna(subset=["time", "dead", "sex"]) # listwise deletion over the analysis columns
df["dead"] = df["dead"].cat.remove_unused_categories()
df["sex"] = df["sex"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["time", "dead", "sex"]) # infinite values stop the run (registry/errors.yaml)
# %% Event coding
tcol = "time"
ecol = "dead"
t = df[tcol].to_numpy(dtype=float)
if (t < 0).any():
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement="zero or positive (survival times)", count=int((t < 0).sum()))
event_level = "true" # the event; other levels are censored
ev = (df[ecol].astype(str) == event_level).to_numpy()
event_label = f"{ecol} = {event_level}"
if not ev.any():
cs.cs_error("CS_E_NO_EVENTS", event=event_label)
# %% Log-rank test
g = "sex"
levels = [str(x) for x in df[g].cat.categories]
if len(levels) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=len(levels))
gv = df[g].astype(str).to_numpy()
codes = np.array([levels.index(x) for x in gv])
sname = None
scodes = None
weights = "logrank"
rho = {"logrank": 0.0, "peto": 1.0, "fh": 0.5}.get(weights, 0.0) # survdiff(rho = …)
gamma = 0 if weights == "fh" else 0.0 # Fleming–Harrington (1 − S(t−))^γ; survdiff has γ = 0 only
test_label = {
"logrank": "The log-rank test", "peto": "The Peto–Peto weighted log-rank test (ρ = 1)",
"gehan": "The Gehan–Breslow (generalized Wilcoxon) test", "tarone_ware": "The Tarone–Ware test",
"peto_prentice": "The Peto–Prentice test", "modified_peto": "The modified Peto–Peto (Andersen) test",
}.get(weights, f"The Fleming–Harrington G(ρ = {rho:g}, γ = {gamma:g}) test" if gamma else f"The Fleming–Harrington G-ρ test (ρ = {rho:g})")
weight_note = {
"gehan": "weights n(t), the number at risk", "tarone_ware": "weights √n(t)",
"peto_prentice": "weights S̃(t) = Π(1 − d/(n + 1)) (Peto's survival estimate)",
"modified_peto": "weights S̃(t)·n/(n + 1) (Andersen et al.)",
}.get(weights, f"weights S(t−)^ρ (1 − S(t−))^γ with ρ = {rho:g}, γ = {gamma:g}, from the pooled Kaplan–Meier curve" if gamma
else f"weights S(t−)^ρ with ρ = {rho:g} from the pooled Kaplan–Meier curve")
def lr_test(tt, ee, gg, ss):
"""survdiff's G-ρ family where it applies; the weighted twin for the other weights."""
if weights in ("logrank", "peto") or (weights == "fh" and gamma == 0):
return sv.logrank(tt, ee, gg, strata=ss, rho=rho)
return sa.logrank_weighted(tt, ee, gg, strata=ss, weights=weights, rho=rho, gamma=gamma)
if sname:
test_label += f", stratified by {sname},"
res = lr_test(t, ev, codes, scodes)
chisq, dof, p = res["chisq"], res["df"], res["p"]
values = {"chisq": chisq, "df": float(dof), "p": p, "n": float(len(t)), "events": float(ev.sum()), "n_groups": float(len(levels)),
"rho": rho, "gamma": gamma, "event_label": event_label, "test_label": test_label}
rows = []
for i, lv in enumerate(levels):
m = codes == i
values[f"n[{lv}]"], values[f"events[{lv}]"] = float(m.sum()), float(ev[m].sum())
values[f"obs[{lv}]"], values[f"exp[{lv}]"] = float(res["obs"][i]), float(res["exp"][i])
rows.append({"group": lv, "n": float(m.sum()), "events": float(ev[m].sum()), "obs": float(res["obs"][i]),
"exp": float(res["exp"][i]), "oe": float((res["obs"][i] - res["exp"][i]) ** 2 / res["exp"][i])})
# %% Pairwise comparisons
pair_rows = []
if True and len(levels) > 2:
pairs = list(combinations(range(len(levels)), 2))
raw = []
for a, b in pairs:
m = (codes == a) | (codes == b)
r = lr_test(t[m], ev[m], (codes[m] == b).astype(int), None if scodes is None else scodes[m])
raw.append((r["chisq"], r["p"]))
adj = p_adjust([x[1] for x in raw], "holm")
for (a, b), (c2, pr), pa in zip(pairs, raw, adj):
key = f"{levels[a]} vs {levels[b]}"
values[f"chisq_pair[{key}]"], values[f"p_pair[{key}]"], values[f"p_pair_adj[{key}]"] = c2, pr, float(pa)
pair_rows.append({"pair": key, "chisq": c2, "p": pr, "p_adj": float(pa)})
# %% Two-group alternatives: supremum, max-combo, restricted mean survival time
test_kind = "rmst"
values.update({"logrank_p": p, "test_kind": test_kind, "renyi_q": None, "renyi_max_u": None, "renyi_var": None, "combo_max_z": None, "tau": None,
"rmst_diff": None, "rmst_diff_se": None, "rmst_diff_low": None, "rmst_diff_high": None, "rmst_z": None})
if test_kind != "chisq" and len(levels) != 2:
raise ValueError(f"This test compares exactly two groups; {g} has {len(levels)}")
extra_tables = []
statistics = [{"key": "chisq", "label": "χ²", "value": chisq}, {"key": "df", "label": "df", "value": float(dof), "format": "integer"}, {"key": "p", "label": "p", "value": p, "format": "p"}]
summary_text = f"{test_label} χ²({dof}) = {chisq:.2f}, {cs.fmt_p(p)}."
apa_text = f"χ²({dof}, N = {len(t)}) = {cs.fmt_num(chisq)}, {cs.fmt_p(p)}"
rmst_tau = None
if test_kind == "renyi":
rn = sa.renyi_test(t, ev, codes, scodes, weights=weights, rho=rho, gamma=gamma)
p = rn["p"]
test_label = "The Rényi supremum test" + (f", stratified by {sname}," if sname else "")
values.update({"p": p, "renyi_q": rn["q"], "renyi_max_u": rn["max_u"], "renyi_var": rn["var"], "test_label": test_label})
statistics = [{"key": "renyi_q", "label": "Q", "value": rn["q"]}, {"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "logrank_p", "label": "Log-rank p", "value": values["logrank_p"], "format": "p"}]
summary_text = f"{test_label.rstrip(',')}: Q = {rn['q']:.3f}, {cs.fmt_p(p)}."
apa_text = f"Q = {cs.fmt_num(rn['q'])}, {cs.fmt_p(p)}"
elif test_kind == "max_combo":
mc = sa.max_combo_test(t, ev, codes, scodes, reps=int(19999), seed=42)
p = mc["p"]
test_label = "The max-combo test" + (f", stratified by {sname}," if sname else "")
values.update({"p": p, "combo_max_z": mc["max_z"], "test_label": test_label})
combo_rows = []
for lab, zv in zip(mc["labels"], mc["z"]):
values[f"combo_z[{lab}]"] = float(zv)
combo_rows.append({"test": lab, "z": float(zv)})
extra_tables.append({"key": "combo", "title": "Fleming–Harrington components", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "z", "label": "Z", "type": "number"}], "rows": combo_rows,
"note": "FH(ρ, γ) weights S(t−)^ρ (1 − S(t−))^γ. The p-value allows for taking the largest of the four."})
statistics = [{"key": "combo_max_z", "label": "Largest |Z|", "value": mc["max_z"]}, {"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "logrank_p", "label": "Log-rank p", "value": values["logrank_p"], "format": "p"}]
summary_text = f"{test_label.rstrip(',')}: largest |Z| = {mc['max_z']:.3f}, {cs.fmt_p(p)}."
apa_text = f"max |Z| = {cs.fmt_num(mc['max_z'])}, {cs.fmt_p(p)}"
elif test_kind == "rmst":
if sname:
raise ValueError("The restricted mean survival difference does not take strata")
rmst_tau = 500 # horizon
rms = []
rm_rows = []
for i, lv in enumerate(levels):
m = codes == i
fit_i = sv.km(t[m], ev[m], conf=0.95, conf_type="log-log")
val_i, se_i = sv.rmst(fit_i, rmst_tau)
rms.append((val_i, se_i))
values[f"rmst[{lv}]"], values[f"rmst_se[{lv}]"] = val_i, se_i
rm_rows.append({"group": lv, "rmst": val_i, "se": se_i})
diff = rms[1][0] - rms[0][0]
se_d = float(np.hypot(rms[0][1], rms[1][1]))
zv = diff / se_d
p = float(2 * stats.norm.sf(abs(zv)))
q_ = float(stats.norm.ppf(0.975))
test_label = "The restricted mean survival time comparison"
values.update({"p": p, "tau": rmst_tau, "rmst_diff": diff, "rmst_diff_se": se_d, "rmst_diff_low": diff - q_ * se_d, "rmst_diff_high": diff + q_ * se_d, "rmst_z": zv, "test_label": test_label})
extra_tables.append({"key": "rmst", "title": f"Restricted mean survival time up to {rmst_tau:g}", "columns": [
{"key": "group", "label": g, "type": "string"}, {"key": "rmst", "label": "RMST", "type": "number"}, {"key": "se", "label": "SE", "type": "number"}], "rows": rm_rows,
"note": f"{levels[1]} minus {levels[0]} = {diff:.4g}, 95% CI [{diff - q_ * se_d:.4g}, {diff + q_ * se_d:.4g}]."})
statistics = [{"key": "rmst_diff", "label": "RMST difference", "value": diff}, {"key": "tau", "label": "Horizon τ", "value": rmst_tau},
{"key": "p", "label": "p", "value": p, "format": "p"}, {"key": "logrank_p", "label": "Log-rank p", "value": values["logrank_p"], "format": "p"}]
summary_text = f"Up to {rmst_tau:g}, mean event-free time differed by {diff:.3g} ({levels[1]} minus {levels[0]}), {cs.fmt_p(p)}."
apa_text = f"RMST difference = {cs.fmt_num(diff)}, 95% CI [{cs.fmt_num(diff - q_ * se_d)}, {cs.fmt_num(diff + q_ * se_d)}], {cs.fmt_p(p)}"
short_title = test_label.removeprefix("The ").rstrip(",")
method_note = {
"rmst": "Each restricted mean is the area under that group's Kaplan–Meier curve up to τ",
"max_combo": "The four tests take their weights from the pooled Kaplan–Meier curve",
}.get(test_kind, f"Test {weight_note}")
# %% Assumptions — Grambsch–Therneau test on a Cox model of the groups
X = np.column_stack([(codes == i).astype(float) for i in range(1, len(levels))])
cox = sv.cox_fit(t, ev, X, strata=scodes, ties="efron")
one_time = np.unique(t[ev]).size < 2 # with every event at one time the proportional-hazards test is undefined
if one_time:
warnings.append(cs.cs_warning("CS_W_TIES", column=tcol, consequence="every event happened at the same time, so the proportional-hazards test is not computed."))
ph_chisq, ph_p = None, None
ph_check = {"key": "proportional_hazards", "label": "Proportional hazards", "status": "info", "detail": "Not tested: every event happened at the same time."}
else:
zph = sv.cox_zph(t, ev, X, cox["coef"], [list(range(X.shape[1]))], strata=scodes, ties="efron")
ph_chisq, _, ph_p = zph["global"]
ph_check = {
"key": "proportional_hazards", "label": "Proportional hazards",
"status": "warn" if ph_p < 0.05 else "pass", "statistic": ph_chisq, "p": ph_p,
"detail": (f"Grambsch–Therneau test χ²({X.shape[1]}) = {ph_chisq:.2f}, {cs.fmt_p(ph_p)}: "
+ ("hazard ratios change over time; the log-rank test loses power when curves cross." if ph_p < 0.05 else "no evidence that hazard ratios change over time.")),
}
values["ph_chisq"], values["ph_p"] = ph_chisq, ph_p
assumptions = [ph_check, {"key": "censoring", "label": "Non-informative censoring", "status": "info",
"detail": f"{int((~ev).sum())} of {len(ev)} observations are censored."}]
low = [r["group"] for r in rows if r["events"] < 5]
assumptions.append({"key": "sample_size", "label": "Number of events", "status": "warn" if low else "pass",
"detail": f"Fewer than 5 events in {', '.join(low)}." if low else "At least 5 events per group."})
# %% Kaplan–Meier curves for the chart
curve = {"time": [], "surv": [], "low": [], "high": [], "strata": [], "nrisk": [], "ncensor": []}
for i, lv in enumerate(levels):
m = codes == i
fit = sv.km(t[m], ev[m], conf=0.95, conf_type="log-log")
nan = lambda x: None if not np.isfinite(x) else float(x) # noqa: E731
curve["time"] += [0.0] + fit["time"].tolist()
curve["surv"] += [1.0] + fit["surv"].tolist()
curve["low"] += [1.0] + [nan(x) for x in fit["lower"]]
curve["high"] += [1.0] + [nan(x) for x in fit["upper"]]
curve["strata"] += [lv] * (len(fit["time"]) + 1)
curve["nrisk"] += [float(m.sum())] + fit["n_risk"].tolist()
curve["ncensor"] += [0.0] + fit["n_censor"].tolist()
# %% Result
tables = [{"key": "groups", "title": "Observed and expected events", "columns": [
{"key": "group", "label": g, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "events", "label": "Events", "type": "integer"}, {"key": "obs", "label": "Observed (weighted)", "type": "number"},
{"key": "exp", "label": "Expected (weighted)", "type": "number"}, {"key": "oe", "label": "(O−E)²/E", "type": "number"},
], "rows": rows}] + extra_tables
if pair_rows:
tables.append({"key": "posthoc", "title": "Pairwise comparisons", "columns": [
{"key": "pair", "label": "Pair", "type": "string"}, {"key": "chisq", "label": "χ²", "type": "number"},
{"key": "p", "label": "p", "type": "pvalue"}, {"key": "p_adj", "label": "p (adjusted)", "type": "pvalue"},
], "rows": pair_rows, "note": "Adjustment: holm."})
cs.publish({
"method": "survival.logrank",
"methodVersion": "1.2.1",
"title": short_title[:1].upper() + short_title[1:] + f" by {g}",
"engine": cs.engine_info("numpy", "scipy", "statsmodels", "codesplash"),
"n": int(len(t)),
"summary": summary_text,
"apa": apa_text,
"statistics": statistics,
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {event_label}. {method_note}" + (f" within strata of {sname}." if sname else ".")],
"charts": [cs.chart("km", "km-curve", f"Kaplan–Meier curves by {g}", {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"low": cs.col("lower", curve["low"], "numeric"), "high": cs.col("upper", curve["high"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels),
"nrisk": cs.col("At risk", curve["nrisk"], "numeric"), "ncensor": cs.col("Censored", curve["ncensor"], "numeric"),
}), cs.chart("loglog", "loglog-survival", f"Log–log survival by {g}", {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels),
})] + ([cs.chart("rmst", "rmst-area", f"Restricted mean survival up to {rmst_tau:g}", {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels),
}, controls={"tau": rmst_tau})] if rmst_tau is not None else []),
"values": values,
})
View data
| days | survival | arm |
|---|---|---|
| 0 | 1 | control |
| 0.4000 | 0.9800 | control |
| 0.6000 | 0.9600 | control |
| 2.300 | 0.9400 | control |
| 3 | 0.9200 | control |
| 4.500 | 0.9000 | control |
| 6.400 | 0.8800 | control |
| 8.500 | 0.8600 | control |
| 10.200 | 0.8400 | control |
| 11.100 | 0.8200 | control |
| 12.100 | 0.8000 | control |
| 14.500 | 0.7800 | control |
| 19.400 | 0.7600 | control |
| 23.700 | 0.7400 | control |
| 24.500 | 0.7200 | control |
| 25 | 0.7000 | control |
| 28 | 0.6800 | control |
| 32.200 | 0.6600 | control |
| 33.400 | 0.6400 | control |
| 35.500 | 0.6200 | control |
| 40.200 | 0.6000 | control |
| 43.900 | 0.5800 | control |
| 44.900 | 0.5600 | control |
| 45.400 | 0.5400 | control |
| 48.100 | 0.5200 | control |
| 51 | 0.5000 | control |
| 51.900 | 0.4800 | control |
| 56.100 | 0.4600 | control |
| 61 | 0.4400 | control |
| 61.300 | 0.4200 | control |
| 61.600 | 0.4000 | control |
| 62.300 | 0.3800 | control |
| 67.100 | 0.3600 | control |
| 67.600 | 0.3400 | control |
| 67.700 | 0.3200 | control |
| 68.700 | 0.3000 | control |
| 70.700 | 0.2800 | control |
| 78.800 | 0.2600 | control |
| 79.800 | 0.2400 | control |
| 82.600 | 0.2200 | control |
| 83.500 | 0.2000 | control |
| 84.100 | 0.1800 | control |
| 88.100 | 0.1600 | control |
| 88.200 | 0.1400 | control |
| 91.800 | 0.1200 | control |
| 94.600 | 0.1000 | control |
| 97.700 | 0.0800 | control |
| 109 | 0.0600 | control |
| 121.50 | 0.0400 | control |
| 126.40 | 0.0200 | control |
| 128.60 | 0 | control |
| 0 | 1 | treated |
| 0.9000 | 0.9800 | treated |
| 5.600 | 0.9600 | treated |
| 10.100 | 0.9400 | treated |
| 13 | 0.9200 | treated |
| 13.500 | 0.9000 | treated |
| 14.700 | 0.8800 | treated |
| 18 | 0.8600 | treated |
| 18.400 | 0.8400 | treated |
First 60 of 102 rows.
Set Time horizon τ before you see the results. Left blank, CodeSplash uses the shorter of the two groups' follow-up.
Same idea in code
ReadBoth languages have packages for restricted means. lifelines estimates each group's area, and survRM2 adds the test. CodeSplash computes these in both engines itself, so its numbers can differ slightly from a package's choice of variance.
import pandas as pd
from lifelines import KaplanMeierFitter
from lifelines.utils import restricted_mean_survival_time as rmst
df = pd.read_csv("lung.csv")
for sex, g in df.groupby("sex"):
km = KaplanMeierFitter().fit(g["time"], g["dead"])
print(sex, rmst(km, t=500))library(survRM2)
df <- read.csv("lung.csv")
fit <- rmst2(df$time, df$dead == "true", as.integer(df$sex == "female"), tau = 500)
print(fit)Check your understanding
CheckpointCheck yourself
Two curves cross at one year, and the log-rank p-value is 0.6. What is the right conclusion?
Show the answer
Answer: b
The log-rank test has low power against crossing hazards. A large p-value there says little about whether the groups differ.
Check yourself
You expect an immunotherapy may have a delayed effect, but you aren't sure, and you want one pre-specified test. Which fits best?
Show the answer
Answer: b
Reporting the smaller of two p-values without correction overstates the evidence. Max-combo builds the correction in.
Check yourself
What must a restricted mean report state to be meaningful?
Show the answer
Answer: b
The difference depends on τ. "82 days" means little without "over the first 500 days".
Recap
Recap- Opposing early and late effects can cancel in a log-rank test.
- The Rényi test uses the largest gap over follow-up; max-combo covers four shapes and corrects for that.
- A restricted mean difference gives a size that survives crossing hazards.
- Choose among them before seeing outcomes, and name the horizon.
Concepts in this lesson