BCompare groups · ttest.paired
Paired t-test
Did the same subjects change between two measurements?
Compares two measurements on the same subjects (before/after, left/right) through the mean of their differences, with Hedges' g_z for the standardized change.
A real result
Example “Sleep”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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.
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.
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
- Sleepsleep_wide · x: drug1 · y: drug2
- Normality lillieforssleep_wide · x: drug1 · y: drug2
- Scores greaterscores · x: after · y: before
- Irisiris · x: Sepal.Length · y: Petal.Length
- Lens paired tosta_xy_wide · x: x · y: y
- Lens minimal effectsleep_wide · x: drug2 · y: drug1
- Signflip exactsleep_wide · x: drug1 · y: drug2
- Signflip greaterscores · x: after · y: before
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 (continuous): paired t, Wilcoxon signed-rank · Statistics Guide · B — Compare groups
- Statistic, p, effect size, CI, adjustment, context · Statistics Guide · Step 4 — Report and interpret
- Regression (linear, GLM), ANOVA, t-tests, chi-square · DS & ML Decision Guide · Explain — why is it happening?
What you need
- First measurementnumeric · 1 column
- e.g. before; the difference is first − second.
- Second measurementnumeric · 1 column
- e.g. after, on the same row (same subject).
Choices you make
hypothesis
- Alternative hypothesisdefault two-sided
Which direction counts as evidence. Keep two-sided unless you fixed the direction before seeing the data.
- Mean difference ≠ 0(default) — Tests for a mean difference other than 0 in either direction; keep it unless you fixed a direction before seeing the data.
- First > second — Tests only for the first measure being higher; pick it only if you fixed this direction before seeing the data.
- First < second — Tests only for the first measure being lower; pick it only if you fixed this direction before seeing the data.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
- Lensdefault none
Also test against bounds you set before seeing the data: equivalence, a minimal effect or non-inferiority.
- Off(default) — Test for a difference only.
- Equivalence (TOST) — Show the effect lies inside your bounds (two one-sided tests).
- Minimal effect — Show the effect lies outside your bounds, i.e. is big enough to matter.
- Non-inferiority — Show the effect is not worse than the lower bound.
- Lower bound (raw units)default —
The smallest effect that matters on the low side (for non-inferiority: the margin, as a negative number).
- Upper bound (raw units)default —
The smallest effect that matters on the high side.
Advanced
- Hypothesized differencedefault 0
The mean difference under the null hypothesis; usually 0 (no change).
- Randomization p-valuedefault none
Add a sign-flip p-value that needs only symmetric differences, not normal ones.
- None(default) — Report only the t-test's p-value.
- Sign-flip test — Flips the signs of the differences: exact over every pattern for up to 16 pairs, else random patterns.
- Random sign patternsdefault 9999
Used above 16 pairs (exact below); the smallest possible p is 1/(B + 1).
- Normality checkdefault shapiro_wilk
Which test the normality row uses. Shapiro–Wilk is the most powerful all-rounder; a check, not a gate.
- Shapiro–Wilk(default) — The default: best overall power for 3–5,000 values.
- Shapiro–Francia — A simpler Shapiro–Wilk (squared correlation with normal scores); good for heavy tails; 5–5,000 values.
- Filliben probability-plot correlation — How straight the normal Q–Q plot is (r); p by simulation (fixed seed).
- Anderson–Darling — Weights the tails heavily; estimated mean and SD; at least 8 values.
- Lilliefors (Kolmogorov–Smirnov) — The largest gap between the ECDF and the fitted normal; least powerful of the EDF tests.
- Cramér–von Mises — Squared ECDF gaps summed over the whole range; at least 8 values.
- D'Agostino–Pearson omnibus (K²) — Combines the skewness and kurtosis z-tests; at least 8 values (20+ preferred).
- Jarque–Bera — Skewness and kurtosis against a χ²(2); needs large samples to be accurate.
- D'Agostino skewness — Asymmetry only (z of the sample skewness); at least 8 values.
- Anscombe–Glynn kurtosis — Tail weight only (z of the sample kurtosis); at least 8 values, rough below 20.
- Pearson χ² — Counts in equiprobable classes of the fitted normal; weakest of the eleven.
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 the differences
Shapiro–Wilk on the paired differences.
- If violated → Wilcoxon signed-rank test — Ranks the differences, so it needs only symmetric (not normal) differences. Changes the question: Tests the pseudo-median difference rather than the mean.
- If violated → Yuen's paired trimmed-means test — Compares 20% trimmed means, which resist outliers and heavy tails. Changes the question: Compares trimmed means.
- If violated → Sign test — Uses only the signs of the differences, so it needs neither normality nor symmetry. Changes the question: Tests the median difference.
Pairs belong togetherNot checked from data: state why it holds
Each row holds both measurements of one subject.
What it reports
- Tests: Mean paired difference
- t
- An estimate divided by its standard error, compared with a t distribution.
- 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.
- mean_diff
- One group's mean minus another's, in the outcome's own units.
- sd_diff
- The typical distance of values from their mean, in the data's own units.
- ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- mean_1
- The sum divided by the count; the balance point of the data, pulled by extreme values.
- mean_2
- The sum divided by the count; the balance point of the data, pulled by extreme values.
- r
- A number from −1 to 1 for how closely two variables move together; Pearson measures straight-line association.
- d_z
- An estimate in standard-error units, compared with the standard normal distribution.
- g_z
- An estimate in standard-error units, compared with the standard normal distribution.
- gz_ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- gz_ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- sw_p
- A test of normality; a small p-value says the data are unlikely to come from a normal distribution.
- mu
- A model of how big the next move is likely to be, built from recent shocks and recent volatility. It says nothing about direction.
Per group, level or term: normality_p (when a non-default normality check is chosen), perm_p, perm_kind, perm_b (when the sign-flip p-value is on), lens_p (when a lens is on), lens_ci_low (when a lens is on), lens_ci_high (when a lens is on), lens_verdict (when a lens is on)
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
- Effect-size intervals invert the noncentral t (scipy: Boost nct; R: AS 243).
The exact script CodeSplash ran for example “Sleep” · 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 []),
})
The exact script CodeSplash ran for example “Sleep” · 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())
))
Sources
- Lakens, D. (2013). Calculating and reporting effect sizes to facilitate cumulative science. Frontiers in Psychology, 4, 863.
From the CodeSplash method registry · ttest.paired v1.3.0.