ADescribe · variance.paired
Paired variance test
Do two measurements on the same subjects have the same spread?
Compares the variances of two paired measurements (two instruments, before/after) through the correlation of their sums and differences: the Pitman–Morgan test with an interval for the variance ratio, or McCulloch's rank version that does not assume normality.
A real result
Example “Pitman morgan guide”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
t(8) = 1.68, p = .132
- t
- 1.675
- df
- 8
- r (sums, differences)
- 0.5096
- p
- .132
Effect size
- Variance ratio (x / y) 2.615 95% CI [0.7237, 9.452]
Assumptions
- Normality of sums and differences — Shapiro–Wilk p ≥ .05 for the sums and the differences.
Spread of each measurement
| Measurement | SD | Variance |
|---|---|---|
| x | 0.6146 | 0.3778 |
| y | 0.3801 | 0.1444 |
- Tests Var(x) = 1 × Var(y) through the correlation of sums and differences (r between the measurements = 0.537).
t(8) = 1.68, p = .132
- t
- 1.675
- df
- 8
- r (sums, differences)
- 0.5096
- p
- .132
Effect size
- Variance ratio (x / y) 2.615 95% CI [0.7237, 9.452]
Assumptions
- Normality of sums and differences — Shapiro–Wilk p ≥ .05 for the sums and the differences.
Spread of each measurement
| Measurement | SD | Variance |
|---|---|---|
| x | 0.6146 | 0.3778 |
| y | 0.3801 | 0.1444 |
- Tests Var(x) = 1 × Var(y) through the correlation of sums and differences (r between the measurements = 0.537).
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
- Pitman morgan guidec3_variance_pairs · x: x · y: y
- Mcculloch guidec3_variance_pairs · x: x · y: y
- Pitman morgan instrumentspefr · x: wright · y: mini wright
- Pitman morgan ratiosleep_wide · x: drug1 · y: drug2
- Mcculloch greaterpefr · x: wright · y: mini wright
- Degenerate constantc3_variance_pairs · x: x · y: y
- Degenerate n3c3_variance_pairs · x: x · y: y
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Assess variance: Levene, Brown–Forsythe · Statistics Guide · A — Describe data
- Paired (continuous): paired t, Wilcoxon signed-rank · Statistics Guide · B — Compare groups
What you need
- First measurementnumeric · 1 column
- e.g. instrument A, or before; the ratio is first ÷ second.
- Second measurementnumeric · 1 column
- e.g. instrument B, or after, on the same row (same subject).
Choices you make
statistics
- Testdefault pitman_morgan
Pitman–Morgan is exact for bivariate normal pairs; McCulloch's rank version is robust to outliers and heavy tails.
- Pitman–Morgan(default) — Pearson correlation of sums and differences (t test), with an interval for the variance ratio.
- McCulloch (rank-based) — Spearman correlation of sums and differences; keeps its error rate with non-normal pairs.
hypothesis
- Alternative hypothesisdefault two-sided
Decide the direction before looking at the data.
- The spreads differ(default) — Either measurement may be more variable.
- First more variable — One-sided: the first measurement has the larger variance.
- First less variable — One-sided: the first measurement has the smaller variance.
- Confidence leveldefault 0.95
Confidence level of the interval for the variance ratio (Pitman–Morgan).
Advanced
- Variance ratio under the nulldefault 1
The ratio first ÷ second variance that the null hypothesis assumes (usually 1).
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.
Normality of sums and differences
Shapiro–Wilk on x + y and x − y; Pitman–Morgan assumes bivariate normal pairs, McCulloch does not.
- If violated → McCulloch test — Uses the rank correlation of sums and differences, so it does not need bivariate normal pairs.
Pairs belong togetherNot checked from data: state why it holds
Each row holds both measurements of one subject.
What it reports
- test
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- statistic
- One test of "every component null holds" from several independent tests' p-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.
- n
- How many independent units the analysis used; it sets precision and power.
- var_ratio
- Compares two variances through their ratio s₁²/s₂² against an F distribution.
- sd_x
- The typical distance of values from their mean, in the data's own units.
- sd_y
- The typical distance of values from their mean, in the data's own units.
- r
- A number from −1 to 1 for how closely two variables move together; Pearson measures straight-line association.
- r_sd
- Tests equal variances of two paired measurements via the correlation between their sums and differences.
- method_label
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- ratio_null
- The ratio of variances the test compares against, 1 unless you set another; the result tests whether the data differ from it.
Per group, level or term: ci_high, ci_low
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.
Default traps between the two languages
- McCulloch's p-value uses the t approximation for Spearman's ρ (R's cor.test(method = 'spearman', exact = FALSE); scipy's spearmanr).
The exact script CodeSplash ran for example “Pitman morgan guide” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Paired variance test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method variance.paired 1.0.1 · spec 3b8f47635f1ee4ce
# Dataset: c3_variance_pairs (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 spread
# %% Data
df = pd.read_parquet("tests/parity/fixtures/c3_variance_pairs.parquet", columns=["x", "y"])
n_input = len(df)
df = df.dropna(subset=["x", "y"]) # listwise deletion over the analysis columns
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, ["x", "y"]) # infinite values stop the run (registry/errors.yaml)
# %% Options
xc, yc = "x", "y"
test = "pitman_morgan" or "pitman_morgan"
alternative = "two-sided" or "two-sided"
ratio = float(1 or 1.0)
conf_level = float(0.95 or 0.95)
# %% Test
x = df[xc].to_numpy(dtype=float)
y = df[yc].to_numpy(dtype=float)
if len(x) < 4:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A paired variance test", min=4, n=len(x))
for column, v in ((xc, x), (yc, y)): # a variance of 0: the variance ratio is 0 or infinite
if len(np.unique(v)) < 2:
cs.cs_error("CS_E_CONSTANT", column=column)
res = spread.variance_paired(x, y, test, ratio=ratio, alternative=alternative, conf_level=conf_level)
warnings.extend(res["warnings"])
n, stat, p, name = res["n"], float(res["statistic"]), float(res["p"]), res["label"]
# %% Assumptions
assumptions = []
if 3 <= n <= 5000:
sw = {"sums": float(stats.shapiro(x + y).pvalue), "differences": float(stats.shapiro(x - y).pvalue)}
bad = [k for k, v in sw.items() if v < 0.05]
if bad and test == "pitman_morgan":
status, detail = "warn", f"Shapiro–Wilk p < .05 for the {' and '.join(bad)}; prefer McCulloch's rank test."
elif bad:
status, detail = "info", f"Shapiro–Wilk p < .05 for the {' and '.join(bad)}; McCulloch's test does not assume normality."
else:
status, detail = "pass", "Shapiro–Wilk p ≥ .05 for the sums and the differences."
else:
status, detail = "info", "Too few (or too many) pairs for Shapiro–Wilk; inspect a scatterplot."
assumptions.append({"key": "normality", "label": "Normality of sums and differences", "status": status, "detail": detail})
# %% Result
dir_text = {"two-sided": "differ in spread", "greater": f"{xc} is more variable", "less": f"{xc} is less variable"}[alternative]
verdict = (f"The measurements {dir_text} ({cs.fmt_p(p)})." if p < 0.05 and alternative == "two-sided"
else f"Evidence that {dir_text} ({cs.fmt_p(p)})." if p < 0.05
else f"No evidence that the measurements differ in spread ({cs.fmt_p(p)}).")
summary = (f"{xc} has SD {res['sd_x']:.4g} and {yc} SD {res['sd_y']:.4g} over {n} pairs (variance ratio {res['var_ratio']:.3g}). "
f"{name}: {verdict}")
values = {"test": test, "statistic": stat, "df": res["df"], "p": p, "n": n, "var_ratio": res["var_ratio"], "sd_x": res["sd_x"],
"sd_y": res["sd_y"], "r": res["r"], "r_sd": res["r_sd"], "ratio_null": ratio, "method_label": name}
for key in ("ci_low", "ci_high"):
v = res.get(key)
if v is not None and math.isfinite(v):
values[key] = float(v)
eff = {"key": "var_ratio", "label": f"Variance ratio ({xc} / {yc})", "value": res["var_ratio"], "method": "s₁² / s₂²"}
if "ci_low" in res and math.isfinite(res["ci_low"]) and math.isfinite(res["ci_high"]):
eff.update({"ciLow": res["ci_low"], "ciHigh": res["ci_high"], "ciLevel": conf_level, "method": "Pitman–Morgan interval"})
r_label = "r (sums, differences)" if test == "pitman_morgan" else "ρ (sums, differences)"
cs.publish({
"method": "variance.paired",
"methodVersion": "1.0.1",
"title": name,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"t({res['df']:g}) = {cs.fmt_num(stat)}, {cs.fmt_p(p)}",
"statistics": [{"key": "statistic", "label": "t", "value": stat}, {"key": "df", "label": "df", "value": res["df"]},
{"key": "r_sd", "label": r_label, "value": res["r_sd"]}, {"key": "p", "label": "p", "value": p, "format": "p"}],
"tables": [{
"key": "spread", "title": "Spread of each measurement",
"columns": [{"key": "measurement", "label": "Measurement", "type": "string"}, {"key": "sd", "label": "SD", "type": "number"},
{"key": "variance", "label": "Variance", "type": "number"}],
"rows": [{"measurement": xc, "sd": res["sd_x"], "variance": res["var_x"]}, {"measurement": yc, "sd": res["sd_y"], "variance": res["var_y"]}],
}],
"effectSizes": [eff],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Tests Var({xc}) = {ratio:g} × Var({yc}) through the correlation of sums and differences (r between the measurements = {res['r']:.3f})."],
"charts": [],
"values": values,
})
The exact script CodeSplash ran for example “Pitman morgan guide” · R version 4.5.1 (2025-06-13)
# Paired variance test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method variance.paired 1.0.1 · spec 3b8f47635f1ee4ce
# Dataset: c3_variance_pairs (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/c3_variance_pairs.parquet", col_select = c("x", "y")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x", "y")]), , 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("x", "y")) # infinite values stop the run (registry/errors.yaml)
# %% Options
xc <- "x"
yc <- "y"
`%||%` <- function(a, b) if (is.null(a)) b else a
test <- "pitman_morgan" %||% "pitman_morgan"
alternative <- "two-sided" %||% "two-sided"
ratio <- as.double(1 %||% 1)
conf_level <- as.double(0.95 %||% 0.95)
# %% Test
x <- as.double(df[[xc]])
y <- as.double(df[[yc]])
if (length(x) < 4) cs_error("CS_E_TOO_FEW_ROWS", what = "A paired variance test", min = 4, n = length(x))
if (length(unique(x)) < 2) cs_error("CS_E_CONSTANT", column = xc) # a variance of 0: the variance ratio is 0 or infinite
if (length(unique(y)) < 2) cs_error("CS_E_CONSTANT", column = yc)
res <- cs_variance_paired(x, y, test, ratio = ratio, alternative = alternative, conf_level = conf_level)
warnings <- c(warnings, res$warnings)
n <- res$n
stat <- res$statistic
p <- res$p
name <- res$label
# %% Assumptions
if (n >= 3 && n <= 5000) {
sw <- c(sums = stats::shapiro.test(x + y)$p.value, differences = stats::shapiro.test(x - y)$p.value)
bad <- names(sw)[sw < 0.05]
if (length(bad) && test == "pitman_morgan") {
status <- "warn"
detail <- sprintf("Shapiro–Wilk p < .05 for the %s; prefer McCulloch's rank test.", paste(bad, collapse = " and "))
} else if (length(bad)) {
status <- "info"
detail <- sprintf("Shapiro–Wilk p < .05 for the %s; McCulloch's test does not assume normality.", paste(bad, collapse = " and "))
} else {
status <- "pass"
detail <- "Shapiro–Wilk p ≥ .05 for the sums and the differences."
}
} else {
status <- "info"
detail <- "Too few (or too many) pairs for Shapiro–Wilk; inspect a scatterplot."
}
assumptions <- list(list(key = "normality", label = "Normality of sums and differences", status = status, detail = detail))
# %% Result
dir_text <- switch(alternative, "two-sided" = "differ in spread", greater = sprintf("%s is more variable", xc),
less = sprintf("%s is less variable", xc))
verdict <- if (p < 0.05 && alternative == "two-sided") {
sprintf("The measurements %s (%s).", dir_text, cs_fmt_p(p))
} else if (p < 0.05) {
sprintf("Evidence that %s (%s).", dir_text, cs_fmt_p(p))
} else {
sprintf("No evidence that the measurements differ in spread (%s).", cs_fmt_p(p))
}
summary <- sprintf("%s has SD %s and %s SD %s over %d pairs (variance ratio %s). %s: %s", xc, formatC(res$sd_x, digits = 4, format = "g"),
yc, formatC(res$sd_y, digits = 4, format = "g"), n, formatC(res$var_ratio, digits = 3, format = "g"), name, verdict)
values <- list(test = test, statistic = stat, df = res$df, p = p, n = n, var_ratio = res$var_ratio, sd_x = res$sd_x,
sd_y = res$sd_y, r = res$r, r_sd = res$r_sd, ratio_null = ratio, method_label = name)
for (key in c("ci_low", "ci_high")) {
v <- res[[key]]
if (!is.null(v) && is.finite(v)) values[[key]] <- v
}
eff <- list(key = "var_ratio", label = sprintf("Variance ratio (%s / %s)", xc, yc), value = res$var_ratio, method = "s₁² / s₂²")
if (!is.null(res$ci_low) && is.finite(res$ci_low) && is.finite(res$ci_high)) {
eff$ciLow <- res$ci_low
eff$ciHigh <- res$ci_high
eff$ciLevel <- conf_level
eff$method <- "Pitman–Morgan interval"
}
r_label <- if (test == "pitman_morgan") "r (sums, differences)" else "ρ (sums, differences)"
cs_publish(list(
method = "variance.paired",
methodVersion = "1.0.1",
title = name,
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("t(%s) = %s, %s", format(res$df), cs_fmt_num(stat), cs_fmt_p(p)),
statistics = list(list(key = "statistic", label = "t", value = stat), list(key = "df", label = "df", value = res$df),
list(key = "r_sd", label = r_label, value = res$r_sd), list(key = "p", label = "p", value = p, format = "p")),
tables = list(list(
key = "spread", title = "Spread of each measurement",
columns = list(list(key = "measurement", label = "Measurement", type = "string"), list(key = "sd", label = "SD", type = "number"),
list(key = "variance", label = "Variance", type = "number")),
rows = data.frame(measurement = c(xc, yc), sd = c(res$sd_x, res$sd_y), variance = c(res$var_x, res$var_y))
)),
effectSizes = list(eff),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Tests Var(%s) = %s × Var(%s) through the correlation of sums and differences (r between the measurements = %.3f).",
xc, format(ratio), yc, res$r)),
charts = list(),
values = values
))
Sources
- Pitman, E. J. G. (1939). A note on normal correlation. Biometrika, 31, 9–12.
- Morgan, W. A. (1939). A test for the significance of the difference between the two variances in a sample from a normal bivariate population. Biometrika, 31, 13–19.
- McCulloch, C. E. (1987). Tests for equality of variances with paired data. Communications in Statistics — Theory and Methods, 16, 1377–1391.
From the CodeSplash method registry · variance.paired v1.0.1.