Skip to content

EProportions & counts · proportion.cochran_q

Cochran's Q test (several paired proportions)

Does the share of yes answers differ across several related measurements on the same subjects?

Compares three or more yes/no measurements taken on the same subjects (several raters, items, conditions or time points) with Cochran's Q, reports Serlin's η²_Q effect size and the proportion per measurement, and follows up with pairwise McNemar tests adjusted for multiple comparisons.

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

A real result

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

Cochran's Q testRecorded · Python and R agreeRecorded 2026-11-17 · 20 values compared
R

Q(2) = 8.47, p = .014, η²_Q = 0.09

Cochran's Q
8.471
df
2
p
.014

Effect size

  • η²_Q (Serlin) 0.0921

Plots

Proportion trueHow large are several estimates, how precise, and which exclude the null?

Wilson intervals per measurement (each ignores the pairing; the test uses it).

View data
Proportion truehighmeasurementlow
0.60870.7361drug A0.4646
0.60870.7361drug B0.4646
0.34780.4923drug C0.2268

Assumptions

  • Related measurements — Each row holds all measurements of one subject.
  • Enough informative subjects — 34 subjects answer differently across measurements (n·k = 102; ≥ 24 is a common rule for the χ² approximation).

Proportion true per measurement

MeasurementtrueProportionLowerUpper
drug A280.60870.46460.7361
drug B280.60870.46460.7361
drug C160.34780.22680.4923

Pairwise McNemar tests

PairYes / noNo / yesDifferenceTestpp (holm)
drug A vs drug B660exact11
drug A vs drug C2080.2609asymptotic0.02330.0700
drug B vs drug C2080.2609asymptotic0.02330.0700
  • Event: true. Pairwise follow-up: McNemar tests, holm adjustment.
Python

Q(2) = 8.47, p = .014, η²_Q = 0.09

Cochran's Q
8.471
df
2
p
.014

Effect size

  • η²_Q (Serlin) 0.0921

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

Assumptions

  • Related measurements — Each row holds all measurements of one subject.
  • Enough informative subjects — 34 subjects answer differently across measurements (n·k = 102; ≥ 24 is a common rule for the χ² approximation).

Proportion true per measurement

MeasurementtrueProportionLowerUpper
drug A280.60870.46460.7361
drug B280.60870.46460.7361
drug C160.34780.22680.4923

Pairwise McNemar tests

PairYes / noNo / yesDifferenceTestpp (holm)
drug A vs drug B660exact11
drug A vs drug C2080.2609asymptotic0.02330.0700
drug B vs drug C2080.2609asymptotic0.02330.0700
  • Event: true. Pairwise follow-up: McNemar tests, holm adjustment.

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

  • Drugss4_drugs · items: drug A, drug B, drug C
  • Drugs exact bonferronis4_drugs · items: drug A, drug B, drug C
  • Items missings4_items · items: q1 agree, q2 agree, q3 agree, q4 agree
  • Items no posthocs4_items · items: q1 agree, q3 agree

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Study design: independent / paired / repeated / clustered · Statistics Guide · Step 0 — Prepare your data
  • Paired proportions: McNemar · Statistics Guide · E — Compare proportions / frequencies
  • Stratified, repeated, multiway, survey · Statistics Guide · E — Compare proportions / frequencies

What you need

Measurementscategorical / boolean · 2–20 columns · 2–2 levels
Two or more yes/no columns measured on the same subjects (one row per subject).

Choices you make

hypothesis

Event leveldefault —

The level counted as "yes" in every column (default the last stored level — true for true/false columns).

Confidence leveldefault 0.95

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

posthoc

Pairwise follow-updefault mcnemar

After a significant Cochran's Q, compare conditions in pairs with McNemar tests to see which differ.

  • Pairwise McNemar tests(default) — Runs a McNemar test for each pair of conditions; pick it to see which ones differ.
  • None — Reports the overall Cochran's Q only; pick it when you need only whether the conditions differ.
Pairwise testdefault auto

How pairwise McNemar p-values are computed. Automatic uses the exact test with few discordant pairs.

  • Automatic: exact if fewer than 25 discordant pairs(default) — Uses the exact test with under 25 discordant pairs and χ² otherwise; the usual choice.
  • Asymptotic χ² (no correction) — Uses χ² with no continuity correction; accurate with many discordant pairs.
  • Exact binomial — Uses the binomial test on discordant pairs; valid at any size, but conservative in small samples.
Adjustmentdefault holm

How p-values are corrected for making several comparisons. Holm limits any false alarm; BH limits the share of false discoveries.

  • Holm(default) — Controls the chance of any false positive and always finds at least as much as Bonferroni; a good default.
  • Bonferroni — Multiplies each p by the number of tests; the plainest and strictest control, best for a few comparisons.
  • Benjamini–Hochberg (FDR) — Controls the expected share of false positives among the findings; pick it when screening many comparisons.
  • None — Reports raw p-values; use it for one planned comparison, or say plainly that the results are exploratory.

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.

  • Related measurements

    Every row holds all measurements of one subject.

  • Enough informative subjects

    The χ² approximation needs enough subjects whose answers differ across measurements (n·k ≥ 24 is a common rule).

What it reports

  • Tests: Equal proportions across measurements
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.
q
Effect size for the difference between two correlations — the difference of their Fisher z values.
df
How much independent information is left to estimate variability after fitting the model.
p
How surprising your data would be if the null hypothesis were true, as a probability.
eta2
The share of total variance explained by an effect in ANOVA; biased upward in small samples.
event
In time-to-event data, the outcome happening (death, failure, churn). Rows without it by the end of follow-up are censored.
n_informative
How many independent units the analysis used; it sets precision and power.

Per group, level or term: prop[<item>], pair_p[<a> vs <b>], pair_p_adj[<a> vs <b>], pair_diff[<a> vs <b>]

Python and R

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

Default traps between the two languages

  • Python calls statsmodels' cochrans_q; R uses the closed form (cs_cat_cochran_q, the same statistic as DescTools::CochranQTest). Pairwise McNemar tests use the shared twins (cs_mcnemar).
Python

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

# Cochran's Q test (several paired proportions)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.cochran_q 1.0.1 · spec 764524039d24024a
# Dataset: s4_drugs (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import itertools

import numpy as np
import pandas as pd
from statsmodels.stats.contingency_tables import cochrans_q

import codesplash as cs
from codesplash.stats import padjust
from codesplash.stats import proportions as csp  # McNemar variants, Wilson intervals (twins of codesplashr)

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

# %% Test
items = ["drug A", "drug B", "drug C"]
levels1 = ["false", "true"]  # stored level order of the first column
event = levels1[-1]  # default: the last level ("true")
for col in items:
    if event not in set(map(str, df[col].cat.categories)) | set(df[col].astype(str)):
        raise ValueError(f"{col} has no level {event!r}: every measurement needs the same two levels")
x = np.column_stack([(df[col].astype(str) == event).to_numpy(dtype=float) for col in items])
n, k = x.shape
conf = 0.95
if n == 0:
    raise ValueError("No complete rows: every subject needs all measurements")

res = cochrans_q(x)  # Cochran (1950); df = k − 1
q, p, dof = float(res.statistic), float(res.pvalue), int(res.df)
eta2 = q / (n * (k - 1))  # Serlin, Carr & Marascuilo (1982)
props = x.mean(axis=0)
row_sums = x.sum(axis=1)
informative = int(np.sum((row_sums > 0) & (row_sums < k)))  # subjects whose answers differ

# %% Post hoc: pairwise McNemar tests
posthoc = "mcnemar"
mc_method = "auto"
adjust = "holm"
pairs = []
if posthoc == "mcnemar" and k > 2:
    for i, j in itertools.combinations(range(k), 2):
        b = int(np.sum((x[:, i] == 1) & (x[:, j] == 0)))
        c = int(np.sum((x[:, i] == 0) & (x[:, j] == 1)))
        method = mc_method if mc_method != "auto" else ("exact" if b + c < 25 else "asymptotic")
        mc = csp.mcnemar(b, c)
        pairs.append({"a": items[i], "b": items[j], "n10": b, "n01": c, "diff": float(props[i] - props[j]),
                      "method": method, "p": mc["p_exact" if method == "exact" else "p_asymptotic"]})
    raw = np.array([pr["p"] for pr in pairs])
    adj = raw if adjust == "none" else padjust.p_adjust(raw, adjust)
    for pr, pa in zip(pairs, adj):
        pr["p_adj"] = float(pa)

# %% Assumptions
assumptions = [
    {"key": "pairing", "label": "Related measurements", "status": "info", "detail": "Each row holds all measurements of one subject."},
    {"key": "sample_size", "label": "Enough informative subjects",
     "status": "pass" if informative * k >= 24 else "warn",
     "detail": f"{informative} subjects answer differently across measurements (n·k = {informative * k}; ≥ 24 is a common rule for the χ² approximation)."},
]

# %% Result
values = {"n": n, "k": k, "q": q, "df": dof, "p": p, "eta2": eta2, "event": event, "n_informative": informative}
for col, pr in zip(items, props):
    values[f"prop[{col}]"] = float(pr)
for pr in pairs:
    key = f"{pr['a']} vs {pr['b']}"
    values[f"pair_p[{key}]"] = pr["p"]
    values[f"pair_p_adj[{key}]"] = pr["p_adj"]
    values[f"pair_diff[{key}]"] = pr["diff"]
wilson = [csp.prop_ci(float(x[:, j].sum()), n, conf, "wilson") for j in range(k)]
tables = [{
    "key": "proportions", "title": f"Proportion {event} per measurement",
    "columns": [{"key": "item", "label": "Measurement", "type": "string"}, {"key": "count", "label": event, "type": "integer"},
                {"key": "prop", "label": "Proportion", "type": "number", "format": "percent"},
                {"key": "low", "label": "Lower", "type": "number", "format": "percent"}, {"key": "high", "label": "Upper", "type": "number", "format": "percent"}],
    "rows": [{"item": col, "count": int(x[:, j].sum()), "prop": float(props[j]), "low": wilson[j][0], "high": wilson[j][1]} for j, col in enumerate(items)],
}]
if pairs:
    tables.append({
        "key": "pairwise", "title": "Pairwise McNemar tests",
        "columns": [{"key": "pair", "label": "Pair", "type": "string"}, {"key": "n10", "label": "Yes / no", "type": "integer"},
                    {"key": "n01", "label": "No / yes", "type": "integer"}, {"key": "diff", "label": "Difference", "type": "number"},
                    {"key": "method", "label": "Test", "type": "string"}, {"key": "p", "label": "p", "type": "number", "format": "p"},
                    {"key": "p_adj", "label": f"p ({adjust})", "type": "number", "format": "p"}],
        "rows": [{"pair": f"{pr['a']} vs {pr['b']}", "n10": pr["n10"], "n01": pr["n01"], "diff": pr["diff"], "method": pr["method"],
                  "p": pr["p"], "p_adj": pr["p_adj"]} for pr in pairs],
    })
cs.publish({
    "method": "proportion.cochran_q",
    "methodVersion": "1.0.1",
    "title": "Cochran's Q test",
    "engine": cs.engine_info("pandas", "numpy", "scipy", "statsmodels"),
    "n": n,
    "summary": f"Across {n} subjects and {k} measurements, Cochran's Q = {q:.2f}, {cs.fmt_p(p)} (η²_Q = {eta2:.3f}).",
    "apa": f"Q({dof}) = {q:.2f}, {cs.fmt_p(p)}, η²_Q = {cs.fmt_num(eta2)}",
    "statistics": [
        {"key": "q", "label": "Cochran's Q", "value": q},
        {"key": "df", "label": "df", "value": dof},
        {"key": "p", "label": "p", "value": p, "format": "p"},
    ],
    "tables": tables,
    "effectSizes": [{"key": "eta2", "label": "η²_Q (Serlin)", "value": eta2, "method": "Q / (n (k − 1))"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Event: {event}. Pairwise follow-up: {'none' if not pairs else f'McNemar tests, {adjust} adjustment'}."],
    "charts": [cs.chart(
        "proportions", "forest", f"Proportion {event}",
        {"label": cs.col("measurement", items), "estimate": cs.col(f"Proportion {event}", [float(v) for v in props]),
         "low": cs.col("low", [w[0] for w in wilson]), "high": cs.col("high", [w[1] for w in wilson])},
        note="Wilson intervals per measurement (each ignores the pairing; the test uses it).",
    )],
    "values": values,
})
R

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

# Cochran's Q test (several paired proportions)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method proportion.cochran_q 1.0.1 · spec 764524039d24024a
# Dataset: s4_drugs (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_cat_cochran_q (= DescTools::CochranQTest), cs_mcnemar, cs_prop_ci, cs_p_adjust

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s4_drugs.parquet", col_select = c("drug A", "drug B", "drug C")))
n_input <- nrow(df)
df[["drug A"]] <- factor(df[["drug A"]], levels = c("false", "true"))  # stored level order
df[["drug B"]] <- factor(df[["drug B"]], levels = c("false", "true"))  # stored level order
df[["drug C"]] <- factor(df[["drug C"]], levels = c("false", "true"))  # stored level order
df <- df[stats::complete.cases(df[c("drug A", "drug B", "drug C")]), , 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("drug A", "drug B", "drug C"))  # infinite values stop the run (registry/errors.yaml)

# %% Test
items <- c("drug A", "drug B", "drug C")
levels1 <- c("false", "true")  # stored level order of the first column
event <- levels1[length(levels1)]  # default: the last level ("true")
for (col in items) {
  if (!event %in% union(as.character(df[[col]]), levels(df[[col]]))) stop(sprintf("%s has no level '%s': every measurement needs the same two levels", col, event))
}
x <- sapply(items, function(col) as.numeric(as.character(df[[col]]) == event))
x <- matrix(x, ncol = length(items))
n <- nrow(x)
k <- ncol(x)
conf <- 0.95
if (n == 0) stop("No complete rows: every subject needs all measurements")

res <- cs_cat_cochran_q(x)  # Cochran (1950); df = k - 1
q <- res$q
p <- res$p
dof <- res$df
eta2 <- res$eta2  # Serlin, Carr & Marascuilo (1982)
props <- colMeans(x)
row_sums <- rowSums(x)
informative <- sum(row_sums > 0 & row_sums < k)  # subjects whose answers differ

# %% Post hoc: pairwise McNemar tests
posthoc <- "mcnemar"
mc_method <- "auto"
adjust <- "holm"
pairs <- list()
if (posthoc == "mcnemar" && k > 2) {
  for (i in 1:(k - 1)) {
    for (j in (i + 1):k) {
      b <- sum(x[, i] == 1 & x[, j] == 0)
      c <- sum(x[, i] == 0 & x[, j] == 1)
      method <- if (mc_method != "auto") mc_method else if (b + c < 25) "exact" else "asymptotic"
      mc <- cs_mcnemar(b, c)
      pairs[[length(pairs) + 1]] <- list(a = items[i], b = items[j], n10 = b, n01 = c, diff = props[i] - props[j],
                                         method = method, p = if (method == "exact") mc$p_exact else mc$p_asymptotic)
    }
  }
  raw <- vapply(pairs, function(pr) pr$p, 0)
  adj <- if (adjust == "none") raw else cs_p_adjust(raw, adjust)
  for (i in seq_along(pairs)) pairs[[i]]$p_adj <- adj[i]
}

# %% Assumptions
assumptions <- list(
  list(key = "pairing", label = "Related measurements", status = "info", detail = "Each row holds all measurements of one subject."),
  list(key = "sample_size", label = "Enough informative subjects", status = if (informative * k >= 24) "pass" else "warn",
       detail = sprintf("%d subjects answer differently across measurements (n·k = %d; ≥ 24 is a common rule for the χ² approximation).", informative, informative * k))
)

# %% Result
values <- list(n = n, k = k, q = q, df = dof, p = p, eta2 = eta2, event = event, n_informative = informative)
for (j in seq_len(k)) values[[sprintf("prop[%s]", items[j])]] <- props[j]
for (pr in pairs) {
  key <- paste(pr$a, "vs", pr$b)
  values[[sprintf("pair_p[%s]", key)]] <- pr$p
  values[[sprintf("pair_p_adj[%s]", key)]] <- pr$p_adj
  values[[sprintf("pair_diff[%s]", key)]] <- pr$diff
}
wilson <- lapply(seq_len(k), function(j) cs_prop_ci(sum(x[, j]), n, conf, "wilson"))
tables <- list(list(
  key = "proportions", title = sprintf("Proportion %s per measurement", event),
  columns = list(list(key = "item", label = "Measurement", type = "string"), list(key = "count", label = event, type = "integer"),
                 list(key = "prop", label = "Proportion", type = "number", format = "percent"),
                 list(key = "low", label = "Lower", type = "number", format = "percent"), list(key = "high", label = "Upper", type = "number", format = "percent")),
  rows = lapply(seq_len(k), function(j) list(item = items[j], count = sum(x[, j]), prop = props[j], low = wilson[[j]][1], high = wilson[[j]][2]))
))
if (length(pairs)) {
  tables[[2]] <- list(
    key = "pairwise", title = "Pairwise McNemar tests",
    columns = list(list(key = "pair", label = "Pair", type = "string"), list(key = "n10", label = "Yes / no", type = "integer"),
                   list(key = "n01", label = "No / yes", type = "integer"), list(key = "diff", label = "Difference", type = "number"),
                   list(key = "method", label = "Test", type = "string"), list(key = "p", label = "p", type = "number", format = "p"),
                   list(key = "p_adj", label = sprintf("p (%s)", adjust), type = "number", format = "p")),
    rows = lapply(pairs, function(pr) list(pair = paste(pr$a, "vs", pr$b), n10 = pr$n10, n01 = pr$n01, diff = pr$diff, method = pr$method,
                                           p = pr$p, p_adj = pr$p_adj))
  )
}
cs_publish(list(
  method = "proportion.cochran_q",
  methodVersion = "1.0.1",
  title = "Cochran's Q test",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = sprintf("Across %d subjects and %d measurements, Cochran's Q = %.2f, %s (η²_Q = %.3f).", n, k, q, cs_fmt_p(p), eta2),
  apa = sprintf("Q(%d) = %.2f, %s, η²_Q = %s", dof, q, cs_fmt_p(p), cs_fmt_num(eta2)),
  statistics = list(
    list(key = "q", label = "Cochran's Q", value = q),
    list(key = "df", label = "df", value = dof),
    list(key = "p", label = "p", value = p, format = "p")
  ),
  tables = tables,
  effectSizes = list(list(key = "eta2", label = "η²_Q (Serlin)", value = eta2, method = "Q / (n (k − 1))")),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Event: %s. Pairwise follow-up: %s.", event, if (!length(pairs)) "none" else sprintf("McNemar tests, %s adjustment", adjust))),
  charts = list(cs_chart(
    "proportions", "forest", paste("Proportion", event),
    list(label = cs_col("measurement", items), estimate = cs_col(paste("Proportion", event), unname(props)),
         low = cs_col("low", vapply(wilson, function(w) w[1], 0)), high = cs_col("high", vapply(wilson, function(w) w[2], 0))),
    note = "Wilson intervals per measurement (each ignores the pairing; the test uses it)."
  )),
  values = values
))

Sources

  • Cochran, W. G. (1950). The comparison of percentages in matched samples. Biometrika, 37, 256–266.
  • Serlin, R. C., Carr, J., & Marascuilo, L. A. (1982). A measure of association for selected nonparametric procedures. Psychological Bulletin, 92, 786–790.
  • Agresti, A. (2002). Categorical Data Analysis (2nd ed.), §12.1. Wiley.

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