Designs: independent, paired, repeated, clustered
Whether your rows are independent matters more than almost any other choice. Learn to spot pairs, repeats and clusters, and what ignoring them does to your error rate.
What runs in CodeSplash
- Paired t-test Verified in Python and R
- Two-sample t-test (Welch / Student, or z test) Verified in Python and R
- Repeated-measures ANOVA (one within factor) Verified in Python and R
- Linear mixed model (random intercepts and slopes) Verified in Python and R
- Wilcoxon signed-rank test Verified in Python and R
- McNemar's test (paired proportions) Verified in Python and R
You will be able to
- Identify whether rows are independent, paired, repeated or clustered
- Explain why pairing shrinks the standard error
- Predict what ignoring clusters does to the false-positive rate
Read first
Four ways rows relate
ReadBefore you pick a test, ask how many rows come from one unit.
| Design | Picture | Examples |
|---|---|---|
| Independent | One row per unit | Patients randomized to two arms |
| Paired | Two linked rows | Before and after; twins; left and right eye |
| Repeated | Several rows per unit | Weekly measurements per patient |
| Clustered | Units grouped | Students in classrooms; visits in clinics |
The tests differ because the information differs. A pair gives you a within-person difference, which an independent design can't.
Why pairing helps
PredictPredict first
Ten people each try two sleep drugs. Their responses under the two drugs correlate at = 0.795. Compared with treating the two columns as independent groups, what does a paired analysis do to the standard error?
Reveal
It helps a lot, because the variance of a difference subtracts the shared part:
High removes person-to-person variation. The paired test gives = −4.06 and p = .003.
Shuffle inside the pair
ExploreWith pairs, the null says each person's two values could have been swapped. So you flip signs instead of shuffling labels. Raise the spread between subjects and see how the paired test holds up.
BExplorable · Flipping signs in paired data
How do you build a null distribution when each subject is their own control?
Which analysis gives the smaller p-value?
Under the null, "after" and "before" are interchangeable within a pair, so each difference could have had either sign. There are 1024 equally likely arrangements.
Commit your prediction above to see the result
Make your prediction to see the result.
t(9) = −4.06, p = .003, g_z = −1.17, 95% CI [−1.94, −0.38]
- t
- −4.062
- df
- 9
- p
- .003
- Mean difference (drug1 − drug2)
- −1.580
- 95% CI
- [−2.460, −0.7001]
Effect size
- Hedges' g_z −1.174 95% CI [−1.936, −0.3789] · large
Plots
View data
| Measurement | Row | Value |
|---|---|---|
| drug1 | 1 | 0.7000 |
| drug1 | 2 | −1.600 |
| drug1 | 3 | −0.2000 |
| drug1 | 4 | −1.200 |
| drug1 | 5 | −0.1000 |
| drug1 | 6 | 3.400 |
| drug1 | 7 | 3.700 |
| drug1 | 8 | 0.8000 |
| drug1 | 9 | 0 |
| drug1 | 10 | 2 |
| drug2 | 1 | 1.900 |
| drug2 | 2 | 0.8000 |
| drug2 | 3 | 1.100 |
| drug2 | 4 | 0.1000 |
| drug2 | 5 | −0.1000 |
| drug2 | 6 | 4.400 |
| drug2 | 7 | 5.500 |
| drug2 | 8 | 1.600 |
| drug2 | 9 | 4.600 |
| drug2 | 10 | 3.400 |
Assumptions
- Normality of the differences — Differences: Shapiro–Wilk p = .033 with fewer than 30 pairs; consider the Wilcoxon signed-rank test.
Descriptives
| Measurement | n | Mean | SD | Median |
|---|---|---|---|---|
| drug1 | 10 | 0.7500 | 1.789 | 0.3500 |
| drug2 | 10 | 2.330 | 2.002 | 1.750 |
| drug1 − drug2 | 10 | −1.580 | 1.230 | −1.300 |
- Difference = drug1 − drug2; alternative: two-sided; H0 difference = 0. Correlation between the measurements r = 0.80.
The exact R script · R R version 4.5.1 (2025-06-13)
# Paired t-test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ttest.paired 1.3.0 · spec e061146ace6ec955
# Dataset: sleep_wide (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/sleep_wide.parquet", col_select = c("drug1", "drug2")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("drug1", "drug2")]), , 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("drug1", "drug2")) # infinite values stop the run (registry/errors.yaml)
# Normality assumption: the test the dialog selected (`normality_test`). Shapiro-Wilk keeps the
# method's own row; any other choice replaces it (cs_normality_test; a simulated p such as
# Filliben's uses the fixed seed 42, so Python draws the same stream).
normality_test <- "shapiro_wilk"
normality_selected <- function(samples, row_label, small) {
res <- lapply(samples, function(s) cs_normality_test(as.numeric(s), normality_test, 42, 1999))
ok <- Filter(function(r) is.finite(r$p), res)
label <- res[[1]]$label
symbol <- res[[1]]$symbol
if (!length(ok)) {
return(list(row = list(key = "normality", label = row_label, status = "info",
detail = sprintf("%s is not available for these sample sizes.", label)), p = NULL))
}
ps <- vapply(ok, function(r) r$p, 0)
p_min <- min(ps)
bad <- sum(ps < 0.05)
status <- if (bad) (if (small) "warn" else "info") else "pass"
tail <- if (status == "warn") "; consider a rank-based or robust method." else "."
row <- if (length(samples) == 1) {
list(key = "normality", label = row_label, status = status, statistic = ok[[1]]$statistic, p = ok[[1]]$p,
detail = paste0(sprintf("%s %s = %.3f, %s", label, symbol, ok[[1]]$statistic, cs_fmt_p(ok[[1]]$p)), tail))
} else {
list(key = "normality", label = row_label, status = status,
detail = paste0(if (bad) sprintf("%s: p < .05 in %d of %d groups (smallest %s)", label, bad, length(ok), cs_fmt_p(p_min))
else sprintf("%s: p ≥ .05 in every group", label), tail))
}
list(row = row, p = p_min)
}
# %% Helpers
ncp_ci <- function(t, df, conf) {
# CI for the noncentrality parameter of an observed t (Steiger & Fouladi 1997)
solve <- function(prob) {
# P(T <= t | ncp) falls as ncp grows: widen a bracket around t until it straddles prob.
f <- function(ncp) suppressWarnings(pt(t, df, ncp)) - prob
lo <- t - 1
hi <- t + 1
step <- 1
while (f(lo) < 0) {
lo <- lo - step
step <- step * 2
}
step <- 1
while (f(hi) > 0) {
hi <- hi + step
step <- step * 2
}
uniroot(f, c(lo, hi), tol = 1e-12)$root
}
alpha <- 1 - conf
c(solve(1 - alpha / 2), solve(alpha / 2))
}
hedges_j <- function(df) {
# Exact small-sample correction J = gamma(df/2) / (sqrt(df/2) * gamma((df - 1)/2))
exp(lgamma(df / 2) - log(sqrt(df / 2)) - lgamma((df - 1) / 2))
}
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
# Benchmark label for an effect size (rule set named in the result)
if (is.null(x) || !is.finite(x)) return("undetermined")
labels[findInterval(abs(x), cuts) + 1]
}
# %% Test
a <- "drug1"
b <- "drug2"
x1 <- df[[a]]
x2 <- df[[b]]
n <- length(x1)
alternative <- "two-sided"
conf <- 0.95
mu <- 0 # hypothesized mean difference (first - second)
if (n < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "A paired t-test", min = 2, n = n)
if (all(x1 == x2)) cs_error("CS_E_ALL_ZERO_DIFFERENCES")
if (length(unique(x1 - x2)) < 2) cs_error("CS_E_CONSTANT", column = sprintf("%s − %s", a, b)) # t is undefined
res <- t.test(x1, x2, paired = TRUE, mu = mu, alternative = sub("-", ".", alternative, fixed = TRUE), conf.level = conf)
t <- unname(res$statistic)
dof <- unname(res$parameter)
p <- res$p.value
diffs <- x1 - x2
mean_d <- mean(diffs)
sd_d <- sd(diffs)
ci_low <- res$conf.int[1]
ci_high <- res$conf.int[2]
# The correlation is undefined when a measurement doesn't vary: NA (published as null).
r <- if (length(unique(x1)) > 1 && length(unique(x2)) > 1) cor(x1, x2) else NA_real_
# Effect size: d_z = mean difference / SD of differences; g_z with the exact J; noncentral-t CI.
dz <- mean_d / sd_d
nc <- ncp_ci(dz * sqrt(n), n - 1, conf)
j <- hedges_j(n - 1)
gz <- dz * j
gz_low <- nc[1] / sqrt(n) * j
gz_high <- nc[2] / sqrt(n) * j
# %% Assumptions
sw <- if (n >= 3 && n <= 5000 && diff(range(diffs)) > 0) shapiro.test(diffs) else NULL
if (is.null(sw)) {
status <- "info"
detail <- "Shapiro–Wilk needs 3–5,000 differences that are not all equal; inspect a Q–Q plot."
} else if (sw$p.value < 0.05 && n < 30) {
status <- "warn"
detail <- sprintf("Differences: Shapiro–Wilk %s with fewer than 30 pairs; consider the Wilcoxon signed-rank test.", cs_fmt_p(sw$p.value))
} else if (sw$p.value < 0.05) {
status <- "info"
detail <- sprintf("Differences: Shapiro–Wilk %s, but with %d pairs the t-test is robust.", cs_fmt_p(sw$p.value), n)
} else {
status <- "pass"
detail <- sprintf("Differences: Shapiro–Wilk W = %.3f, %s.", sw$statistic, cs_fmt_p(sw$p.value))
}
assumptions <- list(list(key = "normality", label = "Normality of the differences", status = status, detail = detail))
if (n < 5) warnings <- c(warnings, "Fewer than 5 pairs; estimates are unstable.")
normality_p <- NULL
if (normality_test != "shapiro_wilk") {
ns_ <- normality_selected(list(diffs), "Normality of the differences", n < 30)
normality_p <- ns_$p
assumptions <- lapply(assumptions, function(a) if (a$key == "normality") ns_$row else a)
}
# %% Result
alpha <- 1 - conf
pct <- sprintf("%.0f%%", conf * 100)
size <- magnitude(gz, c(0.2, 0.5, 0.8))
significance <- if (p < alpha) {
sprintf("The change is statistically significant (%s).", cs_fmt_p(p))
} else {
sprintf("The data are compatible with no change (%s).", cs_fmt_p(p))
}
summary <- sprintf("Across %d pairs, %s − %s averaged %.2f (SD %.2f), %s CI [%.2f, %.2f]. %s The standardized change is %s (g_z = %.2f).",
n, a, b, mean_d, sd_d, pct, ci_low, ci_high, significance, size, gz)
# Lens (equivalence / minimal effect / non-inferiority) on the mean difference, at alpha = 1 - confidence.
lens_kind <- "none"
lens <- NULL
if (lens_kind != "none") lens <- cs_lens(lens_kind, mean_d, sd_d / sqrt(n), dof, NULL, NULL, 1 - conf)
if (!is.null(lens)) summary <- paste(summary, sprintf("Lens (%s): %s (%s).", gsub("_", " ", lens_kind), lens$lens_verdict, cs_fmt_p(lens$lens_p)))
# Optional sign-flip randomization p (Stage 12.7): exact over all 2^n sign patterns for <= 16 pairs, else
# random sign patterns from the shared Wichmann-Hill stream; needs symmetric differences, not normal ones.
perm <- NULL
if ("none" == "sign_flip") perm <- cs_signflip_test(diffs, mu, alternative, as.integer(9999), 42)
if (!is.null(perm)) {
perm_how <- if (perm$kind == "exact") sprintf("exact over all %s sign patterns", format(perm$b, big.mark = ",")) else sprintf("%s random sign patterns", format(perm$b, big.mark = ","))
summary <- paste(summary, sprintf("Sign-flip randomization test: %s (%s).", cs_fmt_p(perm$p), perm_how))
}
values <- list(
t = t, df = dof, p = p, n = n, mean_diff = mean_d, sd_diff = sd_d, ci_low = ci_low, ci_high = ci_high,
mean_1 = mean(x1), mean_2 = mean(x2), r = r,
d_z = dz, g_z = gz, gz_ci_low = gz_low, gz_ci_high = gz_high,
sw_p = if (is.null(sw)) NULL else sw$p.value, mu = mu
)
if (!is.null(lens)) values <- c(values, lens)
if (!is.null(normality_p)) values$normality_p <- normality_p
if (!is.null(perm)) values <- c(values, list(perm_p = perm$p, perm_kind = perm$kind, perm_b = perm$b))
nn <- length(x1)
cs_publish(list(
method = "ttest.paired",
methodVersion = "1.3.0",
title = "Paired t-test",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("t(%.0f) = %s, %s, g_z = %s, %s CI [%s, %s]", dof, cs_fmt_num(t), cs_fmt_p(p), cs_fmt_num(gz), pct, cs_fmt_num(gz_low), cs_fmt_num(gz_high)),
statistics = c(list(
list(key = "t", label = "t", value = t),
list(key = "df", label = "df", value = dof),
list(key = "p", label = "p", value = p, format = "p"),
list(key = "mean_diff", label = sprintf("Mean difference (%s − %s)", a, b), value = mean_d),
list(key = "ci", label = paste(pct, "CI"), value = c(ci_low, ci_high))),
if (!is.null(lens)) list(list(key = "lens_p", label = sprintf("Lens p (%s)", gsub("_", " ", lens_kind)), value = lens$lens_p, format = "p")) else list(),
if (!is.null(perm)) list(list(key = "perm_p", label = "Sign-flip p", value = perm$p, format = "p")) else list()
),
tables = list(list(
key = "descriptives", title = "Descriptives",
columns = list(list(key = "variable", label = "Measurement", type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "mean", label = "Mean", type = "number"), list(key = "sd", label = "SD", type = "number"),
list(key = "median", label = "Median", type = "number")),
rows = data.frame(variable = c(a, b, sprintf("%s − %s", a, b)), n = n,
mean = c(mean(x1), mean(x2), mean_d), sd = c(sd(x1), sd(x2), sd_d),
median = c(median(x1), median(x2), median(diffs)))
)),
effectSizes = list(list(key = "g_z", label = "Hedges' g_z", value = gz, ciLow = gz_low, ciHigh = gz_high, ciLevel = conf,
method = "mean difference / SD of differences, exact J, noncentral-t interval", magnitude = size, ruleSet = "Cohen (1988)")),
assumptions = assumptions,
warnings = warnings,
notes = c(list(sprintf("Difference = %s − %s; alternative: %s; H0 difference = %s. Correlation between the measurements r = %s.",
a, b, alternative, format(mu), if (is.na(r)) "undefined" else sprintf("%.2f", r))),
if (!is.null(lens)) list(sprintf("The lens interval [%.3g, %.3g] is the %.0f%% interval for the mean difference.", lens$lens_ci_low, lens$lens_ci_high, (1 - 2 * (1 - conf)) * 100)) else list(),
if (!is.null(perm)) list(sprintf("Sign-flip p: the statistic Σ(difference − %s) against its values under every sign pattern (exact, p = share at least as extreme) or %s random patterns from the shared seeded stream (seed 42, p = (1 + count) / (B + 1)); valid when the differences are symmetric about %s under H0.", format(mu), format(perm$b, big.mark = ","), format(mu))) else list()),
values = values,
charts = c(list(cs_chart("pairs", "paired-lines", sprintf("%s and %s per row", a, b), list(
subject = cs_col("Row", rep(as.character(seq_len(min(nn, 2500))), 2), "categorical"),
condition = cs_col("Measurement", rep(c(a, b), each = min(nn, 2500)), "categorical", levels = c(a, b)),
value = cs_col("Value", c(head(x1, 2500), head(x2, 2500)), "numeric")))),
if (!is.null(perm)) {
nc <- cs_signflip_null_curve(perm$null)
list(cs_chart("null", "null-distribution", "Sum of the differences under sign flips", list(
x = cs_col("Σ (difference − μ₀)", nc$x), density = cs_col("Density", nc$density),
observed = cs_col("Observed", rep(perm$statistic, length(nc$x)))), controls = list(alternative = alternative)))
} else list())
))
t(9) = −4.06, p = .003, g_z = −1.17, 95% CI [−1.94, −0.38]
- t
- −4.062
- df
- 9
- p
- .003
- Mean difference (drug1 − drug2)
- −1.580
- 95% CI
- [−2.460, −0.7001]
Effect size
- Hedges' g_z −1.174 95% CI [−1.936, −0.3789] · large
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality of the differences — Differences: Shapiro–Wilk p = .033 with fewer than 30 pairs; consider the Wilcoxon signed-rank test.
Descriptives
| Measurement | n | Mean | SD | Median |
|---|---|---|---|---|
| drug1 | 10 | 0.7500 | 1.789 | 0.3500 |
| drug2 | 10 | 2.330 | 2.002 | 1.750 |
| drug1 − drug2 | 10 | −1.580 | 1.230 | −1.300 |
- Difference = drug1 − drug2; alternative: two-sided; H0 difference = 0. Correlation between the measurements r = 0.80.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Paired t-test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ttest.paired 1.3.0 · spec e061146ace6ec955
# Dataset: sleep_wide (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import optimize, special, stats
import codesplash as cs
from codesplash.stats import means as csm
# %% Data
df = pd.read_parquet("tests/parity/fixtures/sleep_wide.parquet", columns=["drug1", "drug2"])
n_input = len(df)
df = df.dropna(subset=["drug1", "drug2"]) # 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, ["drug1", "drug2"]) # infinite values stop the run (registry/errors.yaml)
# Normality assumption: the test the dialog selected (`normality_test`). Shapiro–Wilk keeps the
# method's own row; any other choice replaces it (codesplash.stats.normality.normality_test; a
# simulated p such as Filliben's uses the fixed seed 42, so R draws the same stream).
normality_test = "shapiro_wilk"
def normality_selected(samples, row_label, small):
from codesplash.stats import normality as csn
res = [csn.normality_test(np.asarray(s, dtype=float), normality_test, 42, 1999) for s in samples]
ok = [r for r in res if np.isfinite(r["p"])]
label, symbol = res[0]["label"], res[0]["symbol"]
if not ok:
return {"key": "normality", "label": row_label, "status": "info", "detail": f"{label} is not available for these sample sizes."}, None
p_min = min(r["p"] for r in ok)
bad = sum(r["p"] < 0.05 for r in ok)
status = ("warn" if small else "info") if bad else "pass"
row = {"key": "normality", "label": row_label, "status": status}
if len(samples) == 1:
row.update({"statistic": ok[0]["statistic"], "p": ok[0]["p"],
"detail": f"{label} {symbol} = {ok[0]['statistic']:.3f}, {cs.fmt_p(ok[0]['p'])}" + ("; consider a rank-based or robust method." if status == "warn" else ".")})
else:
row["detail"] = (f"{label}: p < .05 in {bad} of {len(ok)} groups (smallest {cs.fmt_p(p_min)})" if bad
else f"{label}: p ≥ .05 in every group") + ("; consider a rank-based or robust method." if status == "warn" else ".")
return row, p_min
# %% Helpers
def ncp_ci(t, df, conf):
"""CI for the noncentrality parameter of an observed t (Steiger & Fouladi 1997)."""
def solve(prob):
# P(T <= t | ncp) falls as ncp grows: widen a bracket around t until it straddles prob.
f = lambda ncp: stats.nct.cdf(t, df, ncp) - prob # noqa: E731
lo, hi, step = t - 1.0, t + 1.0, 1.0
while f(lo) < 0:
lo, step = lo - step, step * 2
step = 1.0
while f(hi) > 0:
hi, step = hi + step, step * 2
return optimize.brentq(f, lo, hi, xtol=1e-12)
alpha = 1 - conf
return solve(1 - alpha / 2), solve(alpha / 2)
def hedges_j(df):
"""Exact small-sample correction J = Γ(df/2) / (√(df/2) · Γ((df − 1)/2))."""
return float(np.exp(special.gammaln(df / 2) - np.log(np.sqrt(df / 2)) - special.gammaln((df - 1) / 2)))
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
"""Benchmark label for an effect size (rule set named in the result)."""
if x is None or not np.isfinite(x):
return "undetermined"
for cut, label in zip(cuts, labels):
if abs(x) < cut:
return label
return labels[-1]
# %% Test
a, b = "drug1", "drug2"
x1 = df[a].to_numpy(dtype=float)
x2 = df[b].to_numpy(dtype=float)
n = len(x1)
alternative = "two-sided"
conf = 0.95
mu = 0 # hypothesized mean difference (first − second)
if n < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A paired t-test", min=2, n=n)
if np.all(x1 == x2):
cs.cs_error("CS_E_ALL_ZERO_DIFFERENCES")
if len(np.unique(x1 - x2)) < 2: # the differences don't vary: t is undefined
cs.cs_error("CS_E_CONSTANT", column=f"{a} − {b}")
# scipy tests mean(x1 − x2) = 0, so shift x1 by mu and shift the interval back.
res = stats.ttest_rel(x1 - mu, x2, alternative=alternative)
ci = res.confidence_interval(confidence_level=conf)
t, dof, p = float(res.statistic), float(res.df), float(res.pvalue)
diffs = x1 - x2
mean_d, sd_d = diffs.mean(), diffs.std(ddof=1)
ci_low, ci_high = float(ci.low) + mu, float(ci.high) + mu
# The correlation is undefined when a measurement doesn't vary: null, as R's cor() gives NA.
r = float(np.corrcoef(x1, x2)[0, 1]) if len(np.unique(x1)) > 1 and len(np.unique(x2)) > 1 else None
# Effect size: d_z = mean difference / SD of differences; g_z with the exact J; noncentral-t CI.
dz = mean_d / sd_d
nc_low, nc_high = ncp_ci(dz * np.sqrt(n), n - 1, conf)
j = hedges_j(n - 1)
gz, gz_low, gz_high = dz * j, nc_low / np.sqrt(n) * j, nc_high / np.sqrt(n) * j
# Lens (equivalence / minimal effect / non-inferiority) on the mean difference, at α = 1 − confidence.
lens_kind = "none"
lens = None
if lens_kind != "none":
lens = csm.lens(lens_kind, mean_d, sd_d / np.sqrt(n), dof, None, None, 1 - conf)
# Optional sign-flip randomization p (Stage 12.7): exact over all 2ⁿ sign patterns for ≤ 16 pairs, else
# random sign patterns from the shared Wichmann–Hill stream; needs symmetric differences, not normal ones.
perm = None
if "none" == "sign_flip":
from codesplash.stats import signflip
perm = signflip.signflip_test(diffs, mu, alternative, int(9999), 42)
# %% Assumptions
assumptions = []
sw = stats.shapiro(diffs) if 3 <= n <= 5000 and np.ptp(diffs) > 0 else None
if sw is None:
status, detail = "info", "Shapiro–Wilk needs 3–5,000 differences that are not all equal; inspect a Q–Q plot."
elif sw.pvalue < 0.05 and n < 30:
status, detail = "warn", f"Differences: Shapiro–Wilk {cs.fmt_p(sw.pvalue)} with fewer than 30 pairs; consider the Wilcoxon signed-rank test."
elif sw.pvalue < 0.05:
status, detail = "info", f"Differences: Shapiro–Wilk {cs.fmt_p(sw.pvalue)}, but with {n} pairs the t-test is robust."
else:
status, detail = "pass", f"Differences: Shapiro–Wilk W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)}."
assumptions.append({"key": "normality", "label": "Normality of the differences", "status": status, "detail": detail})
if n < 5:
warnings.append("Fewer than 5 pairs; estimates are unstable.")
normality_p = None
if normality_test != "shapiro_wilk":
_row, normality_p = normality_selected([diffs], "Normality of the differences", n < 30)
assumptions = [_row if a["key"] == "normality" else a for a in assumptions]
# %% Result
alpha = 1 - conf
size = magnitude(gz, (0.2, 0.5, 0.8))
significance = (
f"The change is statistically significant ({cs.fmt_p(p)})." if p < alpha
else f"The data are compatible with no change ({cs.fmt_p(p)})."
)
summary = (
f"Across {n} pairs, {a} − {b} averaged {mean_d:.2f} (SD {sd_d:.2f}), {conf:.0%} CI [{ci_low:.2f}, {ci_high:.2f}]. "
f"{significance} The standardized change is {size} (g_z = {gz:.2f})."
)
if lens:
summary += f" Lens ({lens_kind.replace('_', ' ')}): {lens['lens_verdict']} ({cs.fmt_p(lens['lens_p'])})."
if perm:
perm_how = f"exact over all {perm['b']:,} sign patterns" if perm["kind"] == "exact" else f"{perm['b']:,} random sign patterns"
summary += f" Sign-flip randomization test: {cs.fmt_p(perm['p'])} ({perm_how})."
cs.publish({
"method": "ttest.paired",
"methodVersion": "1.3.0",
"title": "Paired t-test",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"t({dof:.0f}) = {cs.fmt_num(t)}, {cs.fmt_p(p)}, g_z = {cs.fmt_num(gz)}, {conf:.0%} CI [{cs.fmt_num(gz_low)}, {cs.fmt_num(gz_high)}]",
"statistics": [
{"key": "t", "label": "t", "value": t},
{"key": "df", "label": "df", "value": dof},
{"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "mean_diff", "label": f"Mean difference ({a} − {b})", "value": mean_d},
{"key": "ci", "label": f"{conf:.0%} CI", "value": [ci_low, ci_high]},
] + ([{"key": "lens_p", "label": f"Lens p ({lens_kind.replace('_', ' ')})", "value": lens["lens_p"], "format": "p"}] if lens else [])
+ ([{"key": "perm_p", "label": "Sign-flip p", "value": perm["p"], "format": "p"}] if perm else []),
"tables": [{
"key": "descriptives", "title": "Descriptives",
"columns": [{"key": "variable", "label": "Measurement", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"},
{"key": "median", "label": "Median", "type": "number"}],
"rows": [
{"variable": a, "n": n, "mean": float(x1.mean()), "sd": float(x1.std(ddof=1)), "median": float(np.quantile(x1, 0.5))},
{"variable": b, "n": n, "mean": float(x2.mean()), "sd": float(x2.std(ddof=1)), "median": float(np.quantile(x2, 0.5))},
{"variable": f"{a} − {b}", "n": n, "mean": float(mean_d), "sd": float(sd_d), "median": float(np.quantile(diffs, 0.5))},
],
}],
"effectSizes": [{"key": "g_z", "label": "Hedges' g_z", "value": gz, "ciLow": gz_low, "ciHigh": gz_high, "ciLevel": conf,
"method": "mean difference / SD of differences, exact J, noncentral-t interval", "magnitude": size, "ruleSet": "Cohen (1988)"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Difference = {a} − {b}; alternative: {alternative}; H0 difference = {mu:g}. Correlation between the measurements r = {'undefined' if r is None else format(r, '.2f')}."]
+ ([f"The lens interval [{lens['lens_ci_low']:.3g}, {lens['lens_ci_high']:.3g}] is the {1 - 2 * (1 - conf):.0%} interval for the mean difference."] if lens else [])
+ ([f"Sign-flip p: the statistic Σ(difference − {mu:g}) against its values under every sign pattern (exact, p = share at least as extreme) or {perm['b']:,} random patterns from the shared seeded stream (seed 42, p = (1 + count) / (B + 1)); valid when the differences are symmetric about {mu:g} under H0."] if perm else []),
"values": {
"t": t, "df": dof, "p": p, "n": n, "mean_diff": mean_d, "sd_diff": sd_d, "ci_low": ci_low, "ci_high": ci_high,
"mean_1": float(x1.mean()), "mean_2": float(x2.mean()), "r": r,
"d_z": dz, "g_z": gz, "gz_ci_low": gz_low, "gz_ci_high": gz_high,
"sw_p": None if sw is None else float(sw.pvalue), "mu": mu,
**(lens or {}),
**({"normality_p": normality_p} if normality_p is not None else {}),
**({"perm_p": perm["p"], "perm_kind": perm["kind"], "perm_b": perm["b"]} if perm else {}),
},
"charts": [cs.chart("pairs", "paired-lines", f"{a} and {b} per row", {
"subject": cs.col("Row", [str(i + 1) for i in range(min(n, 2500))] * 2, "categorical"),
"condition": cs.col("Measurement", [a] * min(n, 2500) + [b] * min(n, 2500), "categorical", levels=[a, b]),
"value": cs.col("Value", np.concatenate([x1[:2500], x2[:2500]]), "numeric")})]
+ ([cs.chart("null", "null-distribution", "Sum of the differences under sign flips", {
"x": cs.col("Σ (difference − μ₀)", signflip.null_curve(perm["null"])[0]),
"density": cs.col("Density", signflip.null_curve(perm["null"])[1]),
"observed": cs.col("Observed", np.full(40, perm["statistic"]))}, controls={"alternative": alternative})] if perm else []),
})
What ignoring clusters costs
ExploreTwenty classrooms, thirty students each. A t test that treats the 600 students as independent has far too much confidence. Raise the intraclass correlation, and compare the two error rates.
BExplorable · When observations come in clusters
What happens to a t test when students come in classrooms and you ignore it?
There is no true effect. How often does the naive t test reject?
Commit your prediction above to see the result
Make your prediction to see the result.
The inflation is the design effect:
With and it is about : 600 students carry the information of about 245. Test at the level of what was assigned, or model the clusters.
Name the design
CheckpointCheck yourself
Each of 40 patients has blood pressure measured before and after a drug. Which is the right test of the mean change?
Show the answer
Answer: b
Two linked measurements per patient: analyze the differences. The independent test ignores the pairing and wastes the correlation.
Check yourself
Ten clinics were randomized to a new protocol, with 80 patients each. A colleague runs a t test on the 800 patients. What is the main problem?
Show the answer
Answer: a
The unit of assignment is the clinic. Analyze clinic means, or use a mixed model, or the effective sample is badly overstated.
Check yourself
Five weekly weight measurements on 30 people, and the question is whether mean weight changes over the weeks. Which method fits?
Show the answer
Answer: b
Same people at each time: within-person correlation must be modeled. One-way ANOVA treats the weeks as different people.
Check yourself
Clusters have members and intraclass correlation . What is the design effect?
Show the answer
Answer: 5.5
. Your effective sample is less than a fifth of the row count.
Tell CodeSplash
In the appIn the Test Chooser's Compare card, the Subject ID role says that the same subjects appear in several rows, and Measurements as columns covers wide data. Setting them moves the suggestion from independent to paired or repeated designs. In Predict, a grouping column leads to a mixed model.
Recap
Recap- Ask how many rows come from one unit before you ask anything else.
- Pairing removes person-to-person variation, which can shrink the standard error a lot.
- Ignoring clusters makes your result look far more certain than it is; the design effect tells you how much.
Concepts in this lesson