The same people twice: the paired t test
When each value has a partner, test the differences. Pairing removes the variation between people, which can change your answer completely.
What runs in CodeSplash
- STAT010Paired Student t test Runs in CodeSplash
- Paired t-test Verified in Python and R
You will be able to
- Recognize paired data from the study design
- Reduce a paired test to a one-sample test on the differences
- Explain how correlation between pairs shrinks the standard error
Read first
Spot the pairs
ReadThe sleep study gave two drugs to the same ten patients. Each patient has two numbers, and those two numbers belong together: a heavy sleeper tends to gain a lot on either drug.
Pairing comes from the design, never from the data file. Before and after, left eye and right eye, twins, matched controls: if you can draw a line between one value and its partner, the data are paired. See pairingPairingTwo measurements on the same unit (before/after, left/right); analyze their differences, not two independent groups..
Predict the effect of pairing
PredictPredict first
The patients' results on the two drugs are correlated: r = 0.80. Both tests use the same mean difference of −1.58 hours.
Which test gives the smaller p-value, one that respects the pairs or one that treats the values as two separate groups?
Reveal
The paired test. Its standard error ignores the differences between patients, so the same mean difference is many more standard errors from zero: t = −4.06, p = .003.
One sample in disguise
ReadTake each patient's difference, then run a one-sample t test against zero:
The variance of a difference is why pairing helps:
The stronger the positive correlation, the more of the variation cancels.
Watch the differences
ExploreIf the drugs were interchangeable, each patient's difference would be as likely to be positive as negative. Flip the signs at random and see how often chance matches the observed mean difference.
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.
Read the result
Readt(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 []),
})
Drug 1 gave 0.750 extra hours and drug 2 gave 2.33. The mean paired difference is −1.58 hours (95% CI −2.46 to −0.70), t(9) = −4.06, p = .003, with Hedges' = −1.17.
The assumption is about the differences: their shape, not the shape of each drug's values. Here the Shapiro–Wilk check on the differences gives p = .033, a flag worth a look with only ten patients.
Check your understanding
CheckpointCheck yourself · choose all that apply
Which of these designs are paired? Choose all that apply.
Show the answer
Answer: a, b, d
Pairing means each value has a specific partner. Two separate groups of people have no partners.
Check yourself
The mean paired difference is −1.58 hours and the differences have standard deviation 1.23, across 10 patients. What is the t statistic? Give two decimals, with its sign.
Show the answer
Answer: -4.06212768338204
The standard error is 1.23 / √10 = 0.389, and −1.58 / 0.389 ≈ −4.06.
Check yourself
What must be roughly normal for a small-sample paired t test?
Show the answer
Answer: c
The test is a one-sample t test on the differences, so only their distribution matters. Each measurement can be skewed as long as the differences behave.
Do it in CodeSplash
In the appChoose the two columns as First measurement and Second measurement. The data need one row per pair. If your data have one row per measurement, reshape them in Prepare first.
import pandas as pd
from scipy import stats
df = pd.read_csv("sleep_wide.csv") # one row per patient
print(stats.ttest_rel(df["drug1"], df["drug2"]))df <- read.csv("sleep_wide.csv") # one row per patient
t.test(df$drug1, df$drug2, paired = TRUE)Notebook exercise · ~8 min
The paired t test in code
Analyze the same patients under two drugs as pairs, and see what treating them as independent groups costs.
- The mean difference
A paired test works on the differences. Store the mean of drug2 minus drug1 in
mean_diff.Show a solution
Pythonmean_diff = (d2 - d1).mean()Rmean_diff <- mean(d2 - d1) - The paired t statistic
Store the paired t statistic for drug2 minus drug1 in
t_paired.Show a solution
Pythont_paired = stats.ttest_rel(d2, d1).statisticRt_paired <- unname(t.test(d2, d1, paired = TRUE)$statistic)
In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.
Recap
Recap- Paired data come from the design: each value has a partner.
- A paired t test is a one-sample t test on the differences.
- Positive correlation between partners shrinks the standard error, so ignoring the pairs throws information away.
Concepts in this lesson