Ordered groups: the Cochran–Armitage trend test
When groups have a natural order, a test of trend asks a sharper question than chi-square. Its answer depends on the scores you give the groups.
What runs in CodeSplash
- STAT072Cochran–Armitage trend test Runs in CodeSplash
- Cochran–Armitage trend test Verified in Python and R
You will be able to
- Explain what a trend test gains over a chi-square test on the same table
- Split a table's chi-square into a trend part and a departure part
- Choose group scores before seeing the results
Order is information
ReadA study of 32,574 births recorded malformations across 5 ordered levels of the mother's drinking. A chi-square test gives the same answer if you shuffle those levels, because it looks for any pattern at all.
The Cochran–Armitage testCochran–Armitage trend testTests for a straight-line trend in a proportion across ordered groups, given a score for each group. gives each group a score , then spends one degree of freedom on a straight-line trend in the proportions across those scores:
Here events occur among people at score , is the overall proportion, and is the size-weighted mean score.
Choose scores
PredictPredict first
The levels are 0, under 1, 1 to 2, 3 to 5, and 6 or more drinks a day. One analyst scores them 1, 2, 3, 4, 5. Another uses midpoints: 0, ½, 1½, 4, 7. How will their trend tests compare?
Reveal
Different, enough to change the conclusion. Equal spacing gives = 1.83, two-sided p = .176. Midpoints give = 6.57, two-sided p = .010. Midpoints put the small group of heaviest drinkers far from the rest.
One total, split two ways
ReadThe table's overall chi-square doesn't depend on the scores. The scores decide how it divides between the trend and the departure from a straight line.
| Scores | Trend (1 df) | Departure (3 df) | Total |
|---|---|---|---|
| Equally spaced | 1.83 | 10.25 | 12.08 |
| Midpoints | 6.57 | 5.51 | 12.08 |
Midpoints leave little behind: departure p = .138. Equal spacing doesn't describe these data, with departure p = .017.
Decide in advance
ReflectBecause the scores change the answer, choose them from what the levels mean, before you see any results. Midpoints suit levels that are ranges of a real quantity. Equal spacing assumes each step is the same size.
A second set of scores is a fair sensitivity check, as long as you report both.
Doses of 0, 10, 20 and 80 mg are being compared. Which scores would you defend, and what would a reviewer ask you about the last group?
Read the result
Readχ²(1, N = 32) = 8.74, p = .002
- z
- −2.956
- χ² trend (N form)
- 8.740
- p
- .002
- Linear-by-linear χ² (N − 1 form)
- 8.467
- p departure from linearity (df = 1)
- .975
Effect size
- Change in proportion per score unit −0.2920
Plots
Wilson intervals.
View data
| high | low | Proportion true | cyl_f |
|---|---|---|---|
| 0.8853 | 0.4795 | 0.7273 | 4 |
| 0.7105 | 0.1864 | 0.4286 | 6 |
| 0.3529 | 0.0485 | 0.1429 | 8 |
Assumptions
- Groups are ordered — Scores: 4 = 1, 6 = 2, 8 = 3.
- Enough events — n·p̄·(1 − p̄) = 7.7.
Proportion with manual = true
| cyl_f | Score | Events | n | Proportion | 90% CI low (Wilson) | 90% CI high (Wilson) |
|---|---|---|---|---|---|---|
| 4 | 1 | 8 | 11 | 0.7273 | 0.4795 | 0.8853 |
| 6 | 2 | 3 | 7 | 0.4286 | 0.1864 | 0.7105 |
| 8 | 3 | 2 | 14 | 0.1429 | 0.0485 | 0.3529 |
- Event: manual = true; alternative: less. The linear-by-linear statistic is (N − 1)/N times the trend χ².
The exact R script · R R version 4.5.1 (2025-06-13)
# Cochran–Armitage trend test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.trend 1.0.1 · spec 431682638f83046b
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_cochran_armitage, cs_prop_ci (twins of codesplash.stats)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mtcars.parquet", col_select = c("cyl_f", "manual")))
n_input <- nrow(df)
df[["cyl_f"]] <- factor(df[["cyl_f"]], levels = c("4", "6", "8")) # stored level order
df[["manual"]] <- factor(df[["manual"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("cyl_f", "manual")]), , 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("cyl_f", "manual")) # infinite values stop the run (registry/errors.yaml)
# %% Test
g <- "cyl_f"
y <- "manual"
stored <- c("4", "6", "8") # stored (ordinal) level order
outcome_levels <- c("false", "true")
event <- outcome_levels[length(outcome_levels)] # default: the last level
if (!event %in% outcome_levels) cs_error("CS_E_NOT_A_LEVEL", level = event, column = y)
all_scores <- seq_along(stored) # equally spaced
gv <- as.character(df[[g]])
hit <- as.character(df[[y]]) == event
counts <- vapply(stored, function(lv) sum(gv == lv), numeric(1))
events <- vapply(stored, function(lv) sum(hit[gv == lv]), numeric(1))
present <- counts > 0
groups <- stored[present]
n_i <- unname(counts[present])
x_i <- unname(events[present])
scores <- as.numeric(all_scores[present])
k <- length(groups)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = g, min = 2, k = k)
alternative <- "less"
conf <- 0.9
ca <- cs_cochran_armitage(x_i, n_i, scores) # N form (= prop.trend.test(x_i, n_i, scores))
z <- ca$z
p <- switch(alternative, "two-sided" = pchisq(ca$chi2, 1, lower.tail = FALSE), greater = pnorm(z, lower.tail = FALSE), less = pnorm(z))
p_lbl <- pchisq(ca$chi2_lbl, 1, lower.tail = FALSE) # Mantel linear-by-linear (N - 1 form)
n <- sum(n_i)
pbar <- ca$pbar
chi2_total <- sum((x_i - n_i * pbar)^2 / (n_i * pbar * (1 - pbar))) # Pearson χ² on the k x 2 table
df_dep <- k - 2
chi2_dep <- chi2_total - ca$chi2
p_dep <- if (df_dep > 0) pchisq(chi2_dep, df_dep, lower.tail = FALSE) else NULL
# %% Assumptions
small <- n * pbar * (1 - pbar)
assumptions <- list(
list(key = "ordering", label = "Groups are ordered", status = "info",
detail = paste0("Scores: ", paste(sprintf("%s = %s", groups, format(scores, trim = TRUE, drop0trailing = TRUE)), collapse = ", "), ".")),
list(key = "sample_size", label = "Enough events", status = if (small >= 5) "pass" else "warn",
detail = sprintf("n·p̄·(1 − p̄) = %.1f%s", small, if (small < 5) " — few events; the normal approximation is rough." else "."))
)
if (!all(present)) warnings <- c(warnings, paste0("Levels without rows were left out: ", paste(stored[!present], collapse = ", "), "."))
# %% Result
props <- x_i / n_i
cis <- lapply(seq_len(k), function(i) cs_prop_ci(x_i[i], n_i[i], conf, "wilson"))
rows <- data.frame(level = groups, score = scores, events = as.integer(x_i), n = as.integer(n_i), proportion = props,
ci_low = vapply(cis, `[`, numeric(1), 1), ci_high = vapply(cis, `[`, numeric(1), 2), row.names = NULL)
pct <- sprintf("%.0f%%", conf * 100)
values <- list(n = n, k = k, events = sum(x_i), pbar = pbar, z = z, chi2 = ca$chi2, p = p, chi2_lbl = ca$chi2_lbl, p_lbl = p_lbl,
chi2_departure = chi2_dep, df_departure = df_dep, p_departure = p_dep, chi2_total = chi2_total, slope = ca$slope, event = event)
for (i in seq_len(k)) {
values[[sprintf("proportion[%s]", groups[i])]] <- props[i]
values[[sprintf("score[%s]", groups[i])]] <- scores[i]
}
cs_publish(list(
method = "proportion.trend",
methodVersion = "1.0.1",
title = "Cochran–Armitage trend test",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = sprintf("Cochran–Armitage trend test across %d ordered levels of %s: z = %.2f, %s; slope %.4f per score unit.", k, g, z, cs_fmt_p(p), ca$slope),
apa = sprintf("χ²(1, N = %d) = %s, %s", as.integer(n), cs_fmt_num(ca$chi2), cs_fmt_p(p)),
statistics = list(
list(key = "z", label = "z", value = z), list(key = "chi2", label = "χ² trend (N form)", value = ca$chi2),
list(key = "p", label = "p", value = p, format = "p"),
list(key = "chi2_lbl", label = "Linear-by-linear χ² (N − 1 form)", value = ca$chi2_lbl),
list(key = "p_departure", label = sprintf("p departure from linearity (df = %d)", df_dep), value = p_dep, format = "p")
),
tables = list(list(
key = "proportions", title = sprintf("Proportion with %s = %s", y, event),
columns = list(
list(key = "level", label = g, type = "string"), list(key = "score", label = "Score", type = "number"),
list(key = "events", label = "Events", type = "integer"), list(key = "n", label = "n", type = "integer"),
list(key = "proportion", label = "Proportion", type = "number"),
list(key = "ci_low", label = sprintf("%s CI low (Wilson)", pct), type = "number"),
list(key = "ci_high", label = sprintf("%s CI high (Wilson)", pct), type = "number")
),
rows = rows
)),
effectSizes = list(list(key = "slope", label = "Change in proportion per score unit", value = ca$slope, method = "weighted least squares of p_i on the scores")),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Event: %s = %s; alternative: %s. The linear-by-linear statistic is (N − 1)/N times the trend χ².", y, event, alternative)),
charts = list(cs_chart(
"trend", "emm-plot", sprintf("Proportion with %s = %s by %s", y, event, g),
list(x = cs_col(g, groups, levels = groups), mean = cs_col(paste("Proportion", event), rows$proportion),
low = cs_col("low", rows$ci_low), high = cs_col("high", rows$ci_high)),
note = "Wilson intervals."
)),
values = values
))
χ²(1, N = 32) = 8.74, p = .002
- z
- −2.956
- χ² trend (N form)
- 8.740
- p
- .002
- Linear-by-linear χ² (N − 1 form)
- 8.467
- p departure from linearity (df = 1)
- .975
Effect size
- Change in proportion per score unit −0.2920
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Groups are ordered — Scores: 4 = 1, 6 = 2, 8 = 3.
- Enough events — n·p̄·(1 − p̄) = 7.7.
Proportion with manual = true
| cyl_f | Score | Events | n | Proportion | 90% CI low (Wilson) | 90% CI high (Wilson) |
|---|---|---|---|---|---|---|
| 4 | 1 | 8 | 11 | 0.7273 | 0.4795 | 0.8853 |
| 6 | 2 | 3 | 7 | 0.4286 | 0.1864 | 0.7105 |
| 8 | 3 | 2 | 14 | 0.1429 | 0.0485 | 0.3529 |
- Event: manual = true; alternative: less. The linear-by-linear statistic is (N − 1)/N times the trend χ².
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Cochran–Armitage trend test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.trend 1.0.1 · spec 431682638f83046b
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import proportions as csp # Cochran–Armitage, Wilson intervals (twins of codesplashr)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=["cyl_f", "manual"])
n_input = len(df)
df["cyl_f"] = pd.Categorical(df["cyl_f"], categories=["4", "6", "8"]) # stored level order
df["manual"] = pd.Categorical(df["manual"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["cyl_f", "manual"]) # listwise deletion over the analysis columns
df["cyl_f"] = df["cyl_f"].cat.remove_unused_categories()
df["manual"] = df["manual"].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, ["cyl_f", "manual"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
g, y = "cyl_f", "manual"
stored = ["4", "6", "8"] # stored (ordinal) level order
outcome_levels = ["false", "true"]
event = outcome_levels[-1] # default: the last level
if event not in outcome_levels:
cs.cs_error("CS_E_NOT_A_LEVEL", level=event, column=y)
all_scores = np.arange(1, len(stored) + 1, dtype=float) # equally spaced
gv = df[g].astype(str)
hit = df[y].astype(str) == event
counts = np.array([float((gv == lv).sum()) for lv in stored])
events = np.array([float(hit[gv == lv].sum()) for lv in stored])
present = counts > 0
groups, n_i, x_i, scores = [lv for lv, ok in zip(stored, present) if ok], counts[present], events[present], all_scores[present]
k = len(groups)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=g, min=2, k=k)
alternative = "less"
conf = 0.9
ca = csp.cochran_armitage(x_i, n_i, scores) # N form (= R's prop.trend.test)
z = ca["z"]
p = {"two-sided": float(stats.chi2.sf(ca["chi2"], 1)), "greater": float(stats.norm.sf(z)), "less": float(stats.norm.cdf(z))}[alternative]
p_lbl = float(stats.chi2.sf(ca["chi2_lbl"], 1)) # Mantel linear-by-linear (N − 1 form)
n, pbar = float(n_i.sum()), ca["pbar"]
chi2_total = float(np.sum((x_i - n_i * pbar) ** 2 / (n_i * pbar * (1 - pbar)))) # Pearson χ² on the k × 2 table
df_dep = k - 2
chi2_dep = chi2_total - ca["chi2"]
p_dep = float(stats.chi2.sf(chi2_dep, df_dep)) if df_dep > 0 else None
# %% Assumptions
small = n * pbar * (1 - pbar)
assumptions = [
{"key": "ordering", "label": "Groups are ordered", "status": "info",
"detail": "Scores: " + ", ".join(f"{lv} = {s:g}" for lv, s in zip(groups, scores)) + "."},
{"key": "sample_size", "label": "Enough events", "status": "pass" if small >= 5 else "warn",
"detail": f"n·p̄·(1 − p̄) = {small:.1f}" + (" — few events; the normal approximation is rough." if small < 5 else ".")},
]
if not present.all():
warnings.append("Levels without rows were left out: " + ", ".join(lv for lv, ok in zip(stored, present) if not ok) + ".")
# %% Result
props = x_i / n_i
rows, result_values = [], {}
for lv, x, m, s in zip(groups, x_i, n_i, scores):
lo, hi = csp.prop_ci(x, m, conf, "wilson")
rows.append({"level": lv, "score": float(s), "events": int(x), "n": int(m), "proportion": x / m, "ci_low": lo, "ci_high": hi})
result_values[f"proportion[{lv}]"] = x / m
result_values[f"score[{lv}]"] = float(s)
summary = f"Cochran–Armitage trend test across {k} ordered levels of {g}: z = {z:.2f}, {cs.fmt_p(p)}; slope {ca['slope']:.4f} per score unit."
cs.publish({
"method": "proportion.trend",
"methodVersion": "1.0.1",
"title": "Cochran–Armitage trend test",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": int(n),
"summary": summary,
"apa": f"χ²(1, N = {int(n)}) = {cs.fmt_num(ca['chi2'])}, {cs.fmt_p(p)}",
"statistics": [
{"key": "z", "label": "z", "value": z}, {"key": "chi2", "label": "χ² trend (N form)", "value": ca["chi2"]},
{"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "chi2_lbl", "label": "Linear-by-linear χ² (N − 1 form)", "value": ca["chi2_lbl"]},
{"key": "p_departure", "label": f"p departure from linearity (df = {df_dep})", "value": p_dep, "format": "p"},
],
"tables": [{
"key": "proportions", "title": f"Proportion with {y} = {event}",
"columns": [{"key": "level", "label": g, "type": "string"}, {"key": "score", "label": "Score", "type": "number"},
{"key": "events", "label": "Events", "type": "integer"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "proportion", "label": "Proportion", "type": "number"},
{"key": "ci_low", "label": f"{conf:.0%} CI low (Wilson)", "type": "number"},
{"key": "ci_high", "label": f"{conf:.0%} CI high (Wilson)", "type": "number"}],
"rows": rows,
}],
"effectSizes": [{"key": "slope", "label": "Change in proportion per score unit", "value": ca["slope"], "method": "weighted least squares of p_i on the scores"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {y} = {event}; alternative: {alternative}. The linear-by-linear statistic is (N − 1)/N times the trend χ²."],
"charts": [cs.chart(
"trend", "emm-plot", f"Proportion with {y} = {event} by {g}",
{"x": cs.col(g, groups, levels=groups), "mean": cs.col(f"Proportion {event}", [r["proportion"] for r in rows]),
"low": cs.col("low", [r["ci_low"] for r in rows]), "high": cs.col("high", [r["ci_high"] for r in rows])},
note="Wilson intervals.",
)],
"values": {
"n": int(n), "k": k, "events": int(x_i.sum()), "pbar": pbar, "z": z, "chi2": ca["chi2"], "p": p,
"chi2_lbl": ca["chi2_lbl"], "p_lbl": p_lbl, "chi2_departure": chi2_dep, "df_departure": float(df_dep), "p_departure": p_dep,
"chi2_total": chi2_total, "slope": ca["slope"], "event": event, **result_values,
},
})
In mtcars, manual gearboxes get rarer as cylinders go up: 8 of 11 four-cylinder cars, 3 of 7 six-cylinder and 2 of 14 eight-cylinder. The proportion changes by −0.29 per score, with z = −2.96 and one-sided p = .002.
The departure test gives p = .975, so a straight line is compatible with the three proportions. Three groups leave little room to see a curve, though.
The trend describes an association, not a cause: cars with more cylinders also differ in many other ways.
Check your understanding
CheckpointCheck yourself
A trend test gives z = −2.956. What is its on 1 degree of freedom? Two decimals.
Show the answer
Answer: 8.73978001504783
Square z: 2.956² ≈ 8.74. The sign shows the direction, which the form loses.
Check yourself
A table has overall = 20, and its trend is 14. What is the departure ?
Show the answer
Answer: 6
20 − 14 = 6, on one degree of freedom fewer than the overall test.
Check yourself
Three equal, equally spaced groups have event rates of 10%, 40% and 10%. What do you expect?
Show the answer
Answer: b
A hump has no overall slope, so the trend test sees nothing. The departure part of the chi-square picks it up. Trend tests are sharper only for the pattern they look for.
Check yourself
Equal spacing gives p = 0.09, so you try midpoints and get p = 0.03. Which report is honest?
Show the answer
Answer: b
Picking scores by their p-value is a forking path. If you can justify midpoints from the meaning of the levels, say so and show the sensitivity to that choice.
Do it in CodeSplash
In the appChoose Ordered groups, Outcome and Event level. Group scores is Equally spaced by default; pick Custom scores and fill in Scores (in level order) for anything else. The test uses the stored order of the levels, which you set in the data dictionary. A wrong order gives a meaningless trend.
import numpy as np
from scipy import stats
events = np.array([48, 38, 5, 1, 1])
totals = np.array([17114, 14502, 793, 127, 38])
scores = np.array([0, 0.5, 1.5, 4, 7])
p = events.sum() / totals.sum()
mean_score = (totals * scores).sum() / totals.sum()
z = (events * (scores - mean_score)).sum() / np.sqrt(
p * (1 - p) * (totals * (scores - mean_score) ** 2).sum()
)
print(z, z**2, 2 * stats.norm.sf(abs(z)))prop.trend.test(
c(48, 38, 5, 1, 1),
c(17114, 14502, 793, 127, 38),
score = c(0, 0.5, 1.5, 4, 7)
)Recap
Recap- A trend test spends one degree of freedom on a straight line through the proportions.
- The scores change the answer, so fix them in advance and show any sensitivity check.
- Report the departure test too: a trend can be real and still describe the table badly.