Skip to content

EProportions & counts · proportion.trend

Cochran–Armitage trend test

Does the share of an outcome rise or fall across ordered groups?

Tests for a linear trend in proportions across ordered groups (Cochran–Armitage, N form — R's prop.trend.test) with the Mantel linear-by-linear statistic, the departure from linearity and the weighted slope of the proportion per score unit.

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

A real result

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

Cochran–Armitage trend testRecorded · Python and R agreeRecorded 2026-11-17 · 25 values compared
R

χ²(1, N = 32574) = 1.83, p = .176

z
1.352
χ² trend (N form)
1.828
p
.176
Linear-by-linear χ² (N − 1 form)
1.828
p departure from linearity (df = 3)
.017

Effect size

  • Change in proportion per score unit 0.0007

Plots

Proportion with malformation = present by alcoholWhat does the model predict for each group (and does the effect of one factor depend on another)?

Wilson intervals.

View data
highlowProportion presentalcohol
0.00370.00210.00280
0.00360.00190.0026<1
0.01470.00270.00631-2
0.04330.00140.00793-5
0.13490.00470.0263>=6

Assumptions

  • Groups are ordered — Scores: 0 = 1, <1 = 2, 1-2 = 3, 3-5 = 4, >=6 = 5.
  • Enough events — n·p̄·(1 − p̄) = 92.7.

Proportion with malformation = present

alcoholScoreEventsnProportion95% CI low (Wilson)95% CI high (Wilson)
014817,1140.00280.00210.0037
<123814,5020.00260.00190.0036
1-2357930.00630.00270.0147
3-5411270.00790.00140.0433
>=651380.02630.00470.1349
  • Event: malformation = present; alternative: two-sided. The linear-by-linear statistic is (N − 1)/N times the trend χ².
Python

χ²(1, N = 32574) = 1.83, p = .176

z
1.352
χ² trend (N form)
1.828
p
.176
Linear-by-linear χ² (N − 1 form)
1.828
p departure from linearity (df = 3)
.017

Effect size

  • Change in proportion per score unit 0.0007

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

Assumptions

  • Groups are ordered — Scores: 0 = 1, <1 = 2, 1-2 = 3, 3-5 = 4, >=6 = 5.
  • Enough events — n·p̄·(1 − p̄) = 92.7.

Proportion with malformation = present

alcoholScoreEventsnProportion95% CI low (Wilson)95% CI high (Wilson)
014817,1140.00280.00210.0037
<123814,5020.00260.00190.0036
1-2357930.00630.00270.0147
3-5411270.00790.00140.0433
>=651380.02630.00470.1349
  • Event: malformation = present; alternative: two-sided. The linear-by-linear statistic is (N − 1)/N times the trend χ².

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Malformation indexmalformation · group: alcohol · outcome: malformation
  • Malformation scoresmalformation · group: alcohol · outcome: malformation
  • Cylinders manualmtcars · group: cyl_f · outcome: manual
  • Degenerate single levelmalformation · group: alcohol · outcome: malformation

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Ordinal variables: Spearman / Kendall, polychoric · Statistics Guide · C — Test association
  • Trend across ordered groups · Statistics Guide · E — Compare proportions / frequencies

What you need

Ordered groupscategorical · 1 column · 2–30 levels
Groups in their stored (ordinal) order — set the order in the data dictionary.
Outcomecategorical / boolean · 1 column · 2–30 levels
The event level counts as a success; every other level is a non-event.

Choices you make

hypothesis

Event leveldefault —

The outcome level counted as the event (default the last stored level).

Group scoresdefault index

Scores for the ordered groups: equally spaced, or your own (for example, actual doses).

  • Equally spaced (1, 2, 3, …)(default) — Uses 1, 2, 3 …; pick it when the levels are equally spaced.
  • Custom scores — Uses the scores you enter; pick it when levels have real values, such as doses.
Scores (in level order)default

One score per stored level of the group column, e.g. dose or the midpoint of each band.

Alternative hypothesisdefault two-sided

Which direction counts as evidence. Keep two-sided unless you fixed the direction before seeing the data.

  • Any linear trend(default) — Tests for a linear trend in either direction; keep it unless you fixed a direction before seeing the data.
  • Proportion increases with the score — Tests only for the proportion rising with the score; pick it only if you fixed this direction before seeing the data.
  • Proportion decreases with the score — Tests only for the proportion falling with the score; pick it only if you fixed this direction before seeing the data.
Confidence leveldefault 0.95

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

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Groups are ordered

    The test needs a meaningful order (and scores) for the groups.

  • Enough events

    The normal approximation needs enough events and non-events overall (n·p̄·(1 − p̄) ≥ 5 or so).

What it reports

  • Tests: Linear trend in proportions
  • Tests: Departure from a linear trend
n
How many independent units the analysis used; it sets precision and power.
k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
events
In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.
pbar
A value between 0 and 1 — a share, a rate or a probability.
z
An estimate in standard-error units, compared with the standard normal distribution.
chi2
A sum of squared, scaled differences between observed and expected counts or estimates.
p
How surprising your data would be if the null hypothesis were true, as a probability.
chi2_lbl
Mantel's linear-by-linear χ² for trend, on 1 df: the Cochran–Armitage χ² times (N − 1)/N, so slightly smaller.
p_lbl
Two-sided p-value of the linear-by-linear χ² on 1 df, whichever alternative the main Cochran–Armitage test used.
chi2_departure
A sum of squared, scaled differences between observed and expected counts or estimates.
df_departure
How much independent information is left to estimate variability after fitting the model.
p_departure
How surprising your data would be if the null hypothesis were true, as a probability.
chi2_total
A sum of squared, scaled differences between observed and expected counts or estimates.
slope
A rank-based line through two methods' readings (median of pairwise slopes) that allows for error in both and resists outliers.
event
In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.

Per group, level or term: proportion[<level>], score[<level>]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Python

The exact script CodeSplash ran for example “Malformation index” · 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 36f2d8e194c6ee8f
# Dataset: malformation (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/malformation.parquet", columns=["alcohol", "malformation"])
n_input = len(df)
df["alcohol"] = pd.Categorical(df["alcohol"], categories=["0", "<1", "1-2", "3-5", ">=6"])  # stored level order
df["malformation"] = pd.Categorical(df["malformation"], categories=["absent", "present"])  # stored level order
df = df.dropna(subset=["alcohol", "malformation"])  # listwise deletion over the analysis columns
df["alcohol"] = df["alcohol"].cat.remove_unused_categories()
df["malformation"] = df["malformation"].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, ["alcohol", "malformation"])  # infinite values stop the run (registry/errors.yaml)

# %% Test
g, y = "alcohol", "malformation"
stored = ["0", "<1", "1-2", "3-5", ">=6"]  # stored (ordinal) level order
outcome_levels = ["absent", "present"]
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 = "two-sided"
conf = 0.95

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

The exact script CodeSplash ran for example “Malformation index” · 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 36f2d8e194c6ee8f
# Dataset: malformation (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/malformation.parquet", col_select = c("alcohol", "malformation")))
n_input <- nrow(df)
df[["alcohol"]] <- factor(df[["alcohol"]], levels = c("0", "<1", "1-2", "3-5", ">=6"))  # stored level order
df[["malformation"]] <- factor(df[["malformation"]], levels = c("absent", "present"))  # stored level order
df <- df[stats::complete.cases(df[c("alcohol", "malformation")]), , 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("alcohol", "malformation"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
g <- "alcohol"
y <- "malformation"
stored <- c("0", "<1", "1-2", "3-5", ">=6")  # stored (ordinal) level order
outcome_levels <- c("absent", "present")
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 <- "two-sided"
conf <- 0.95

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
))

Sources

  • Cochran, W. G. (1954). Some methods for strengthening the common χ² tests. Biometrics, 10, 417–451.
  • Armitage, P. (1955). Tests for linear trends in proportions and frequencies. Biometrics, 11, 375–386.
  • Agresti, A. (2013). Categorical Data Analysis (3rd ed.), §3.4.6. Wiley.

From the CodeSplash method registry · proportion.trend v1.0.1.