Skip to content

BBayesian · bayes.ttest

Bayesian t-test (JZS Bayes factor)

How much more likely are the data if the means differ than if they are the same?

The Jeffreys–Zellner–Siow Bayes factor for one sample, paired measurements or two independent groups: the evidence for a standardized effect δ (Cauchy prior of width r) against δ = 0, in either direction. Reports the posterior of δ with a credible interval, how the Bayes factor depends on the prior width, and how it grew as rows accumulated. A Bayes factor is relative evidence, not a p-value.

Verified in Python and R Python and R agree to 10 decimals Also called JZS Bayes factor, Bayesian t test, Jeffreys–Zellner–Siow…

A real result

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

Bayesian two-sample t-testRecorded · Python and R agreeRecorded 2026-11-17 · 21 values compared
R

BF₁₀ = 3.53 (JZS, r = 0.707), δ = 0.89, 95% CrI [0.03, 1.88]

BF₁₀ (δ ≠ 0 vs δ = 0)
3.526
BF₀₁
0.2836
δ (posterior median)
0.8945
95% credible interval
[0.0313, 1.884]
t
2.626
df
18

Effect size

  • δ (posterior median) 0.8945 95% CI [0.0313, 1.884]

Plots

Prior and posterior of δHow did the data move belief about the effect, and how much more (or less) plausible is the null value now?
View data
curvedensityδ (standardized effect)
Prior0.0299−2.652
Prior0.0304−2.630
Prior0.0308−2.607
Prior0.0313−2.585
Prior0.0318−2.563
Prior0.0324−2.541
Prior0.0329−2.519
Prior0.0334−2.497
Prior0.0340−2.475
Prior0.0345−2.453
Prior0.0351−2.431
Prior0.0357−2.409
Prior0.0363−2.386
Prior0.0370−2.364
Prior0.0376−2.342
Prior0.0383−2.320
Prior0.0389−2.298
Prior0.0396−2.276
Prior0.0403−2.254
Prior0.0411−2.232
Prior0.0418−2.210
Prior0.0426−2.188
Prior0.0434−2.166
Prior0.0442−2.143
Prior0.0450−2.121
Prior0.0459−2.099
Prior0.0468−2.077
Prior0.0477−2.055
Prior0.0486−2.033
Prior0.0495−2.011
Prior0.0505−1.989
Prior0.0515−1.967
Prior0.0526−1.945
Prior0.0536−1.922
Prior0.0547−1.900
Prior0.0559−1.878
Prior0.0570−1.856
Prior0.0583−1.834
Prior0.0595−1.812
Prior0.0608−1.790
Prior0.0621−1.768
Prior0.0634−1.746
Prior0.0649−1.724
Prior0.0663−1.701
Prior0.0678−1.679
Prior0.0693−1.657
Prior0.0709−1.635
Prior0.0726−1.613
Prior0.0743−1.591
Prior0.0760−1.569
Prior0.0778−1.547
Prior0.0797−1.525
Prior0.0816−1.503
Prior0.0836−1.481
Prior0.0857−1.458
Prior0.0878−1.436
Prior0.0900−1.414
Prior0.0923−1.392
Prior0.0947−1.370
Prior0.0971−1.348

First 60 of 482 rows.

Bayes factor across prior widthsWould a wider or narrower prior change the conclusion?
View data
BF₁₀prior width r
1.4050.0500
1.4480.0557
1.4950.0621
1.5470.0692
1.6040.0771
1.6650.0859
1.7320.0958
1.8050.1067
1.8830.1189
1.9670.1325
2.0580.1477
2.1540.1646
2.2550.1834
2.3620.2044
2.4740.2278
2.5890.2538
2.7070.2828
2.8260.3152
2.9440.3513
3.0600.3914
3.1700.4362
3.2730.4861
3.3650.5417
3.4430.6037
3.5040.6727
3.5260.7071
3.5460.7497
3.5650.8354
3.5600.9310
3.5441
3.5311.037
3.4761.156
3.3951.288
3.3081.414
3.2921.436
3.1681.600
Bayes factor as rows accumulateHow did the evidence grow as the observations came in?
View data
BF₁₀rows
2.09512
2.08413
1.81914
1.56115
2.50116
3.11717
4.22118
3.27319
3.52620

Assumptions

  • Normality — Shapiro–Wilk p ≥ .05.
  • Equal variances — Brown–Forsythe F = 2.67, p = .120; variance ratio 2.62. The JZS model has one common variance.
  • Independent observations — Each row should be a separate subject (pairs share a row).

Descriptives

SamplenMeanSD
x105.3000.6146
y104.7000.3801

Evidence

QuantityValue
BF₁₀ (chosen alternative)3.526
BF₁₀ (two-sided)3.526
P(H₁ | data), equal prior odds0.7790
Posterior mean of δ0.9109
Numerical error of BF (%)4.106e-9
  • Effect: x − y; prior δ ~ Cauchy(0, 0.707).
  • Evidence: moderate evidence for H₁. With equal prior odds, P(H₁ | data) = 0.779.
  • A Bayes factor compares how well two hypotheses predicted the data; it is not a p-value and is not entered in the multiple-testing ledger.
Python

BF₁₀ = 3.53 (JZS, r = 0.707), δ = 0.89, 95% CrI [0.03, 1.88]

BF₁₀ (δ ≠ 0 vs δ = 0)
3.526
BF₀₁
0.2836
δ (posterior median)
0.8945
95% credible interval
[0.0313, 1.884]
t
2.626
df
18

Effect size

  • δ (posterior median) 0.8945 95% CI [0.0313, 1.884]

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

Assumptions

  • Normality — Shapiro–Wilk p ≥ .05.
  • Equal variances — Brown–Forsythe F = 2.67, p = .120; variance ratio 2.62. The JZS model has one common variance.
  • Independent observations — Each row should be a separate subject (pairs share a row).

Descriptives

SamplenMeanSD
x105.3000.6146
y104.7000.3801

Evidence

QuantityValue
BF₁₀ (chosen alternative)3.526
BF₁₀ (two-sided)3.526
P(H₁ | data), equal prior odds0.7790
Posterior mean of δ0.9109
Numerical error of BF (%)4.106e-9
  • Effect: x − y; prior δ ~ Cauchy(0, 0.707).
  • Evidence: moderate evidence for H₁. With equal prior odds, P(H₁ | data) = 0.779.
  • A Bayes factor compares how well two hypotheses predicted the data; it is not a p-value and is not entered in the multiple-testing ledger.

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

  • Guide two samplea_xy_long · group: sample · outcome: value
  • Guide greatera_xy_long · group: sample · outcome: value
  • Toothgrowth widetoothgrowth · group: supp · outcome: len
  • Paired sleepsleep_wide · outcome: drug1 · second: drug2
  • One sample lessa_xy_wide · outcome: x
  • Degenerate constanta_xy_long · group: sample · outcome: value
  • Degenerate single levela_xy_long · group: sample · outcome: value

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • One sample (continuous): one-sample t, Wilcoxon signed-rank · Statistics Guide · B — Compare groups
  • Two independent groups (continuous): Student / Welch t, Mann–Whitney U · Statistics Guide · B — Compare groups
  • Paired (continuous): paired t, Wilcoxon signed-rank · Statistics Guide · B — Compare groups
  • Probabilistic forecasting (Bayesian, deep ensembles) · DS & ML Decision Guide · Predict — forecast or classify outcomes

What you need

Outcomenumeric · 1 column
The numeric variable. Add Groups for two independent groups, a second measurement for pairs, or neither to test against a value.
Groups (two independent groups)categorical / boolean · 0–1 column · 2–2 levels
Exactly two groups; δ is (first level − second level) / pooled SD.
Second measurement (paired)numeric · 0–1 column
For paired data on the same row (e.g. after); δ is the mean of outcome − second divided by its SD.

Choices you make

hypothesis

Prior width on δdefault medium

The Cauchy scale r: half of the prior mass on δ lies in (−r, r). State it when reporting; the robustness chart shows the alternatives.

  • Medium (r = √2/2 ≈ 0.707)(default) — The conventional default: moderate effects expected.
  • Wide (r = 1) — Larger effects expected; a little more favorable to H₀ when the effect is small.
  • Ultrawide (r = √2 ≈ 1.41) — Very large effects expected; favors H₀ more for small effects.
  • Custom — Any positive Cauchy scale r.
Prior scale rdefault 0.707

Cauchy scale of the prior on the standardized effect δ.

Alternative hypothesisdefault two-sided

Directional hypotheses put the whole prior on one side; decide before seeing the data.

  • δ ≠ 0 (either direction)(default) — Prior on both sides of zero.
  • δ > 0 — Prior on positive effects only (first group / outcome higher).
  • δ < 0 — Prior on negative effects only (first group / outcome lower).
Credible leveldefault 0.95

Equal-tailed posterior interval for δ under H₁.

Advanced

Test value / null differencedefault 0

One sample: the reference value; pairs or groups: the difference under H₀ (usually 0).

Robustness across prior widthsdefault on

Recompute the Bayes factor for prior widths from 0.05 to 1.6 (chart).

Sequential Bayes factordefault on

Recompute the Bayes factor on the first n rows in the dataset's order (chart).

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

    Shapiro–Wilk per group (or of the differences); the t likelihood assumes normal data.

    • If violated → Mann–Whitney U test (frequentist) — Rank-based and robust to skew and outliers in small samples. Changes the question: Compares distributions (Hodges–Lehmann shift) with a p-value, not a Bayes factor for δ.
  • Equal variances

    Two groups only: the JZS model has one common variance (Brown–Forsythe check).

    • If violated → Welch's t-test (frequentist) — The JZS two-sample model has one variance; Welch's test allows unequal variances (there is no default unequal-variance Bayes factor). Changes the question: A p-value and confidence interval for the mean difference instead of a Bayes factor.
  • Independent observations

    Each row is a separate subject; use Second measurement for repeated measures.

What it reports

bf10
How much more likely the data are under one hypothesis than another; it can support H₀ as well as H₁.
bf01
The same Bayes factor on other scales: BF₀₁ = 1/BF₁₀ counts evidence for H₀, and log BF₁₀ is its natural log.
log_bf10
The same Bayes factor on other scales: BF₀₁ = 1/BF₁₀ counts evidence for H₀, and log BF₁₀ is its natural log.
bf10_two_sided
How much more likely the data are under one hypothesis than another; it can support H₀ as well as H₁.
p_h1
How probable each model is after the data, given equal prior probabilities for the models compared.
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.
n_eff
How many independent units the analysis used; it sets precision and power.
r
A number from −1 to 1 for how closely two variables move together; Pearson measures straight-line association.
delta_mean
Your belief about a parameter after combining the prior with the data.
delta_median
Your belief about a parameter after combining the prior with the data.
delta_low
A range of effect values compatible with your data at the chosen confidence level.
delta_high
A range of effect values compatible with your data at the chosen confidence level.
n
How many independent units the analysis used; it sets precision and power.
n_1
How many independent units the analysis used; it sets precision and power.
n_2
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.
error_pct
Estimated error of the numerical integration behind the Bayes factor, in percent of its value (ANOVA: the largest over models).
design
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
bf_robust_min
How the Bayes factor changes across prior widths; a conclusion that holds for the conventional widths is robust.
bf_robust_max
How the Bayes factor changes across prior widths; a conclusion that holds for the conventional widths is robust.

Python and R

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

Default traps between the two languages

  • BayesFactor::ttestBF (oracle) integrates with QUADPACK; both engines here use one shared adaptive Gauss–Kronrod rule, agreeing with ttestBF to ≈1e-9.
  • Posterior summaries are exact numerical quantiles; BayesFactor's posterior() samples by MCMC, so its quantiles differ in the third decimal.
Python

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

# Bayesian t-test (JZS Bayes factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.ttest 1.0.1 · spec dbff3bb54fdc088d
# Dataset: a_xy_long (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 bayes as bf  # JZS Bayes factor, posterior of δ (twin of R cs_bayes_*)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/a_xy_long.parquet", columns=["value", "sample"])
n_input = len(df)
df["sample"] = pd.Categorical(df["sample"], categories=["x", "y"])  # stored level order
df = df.dropna(subset=["value", "sample"])  # listwise deletion over the analysis columns
df["sample"] = df["sample"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["value", "sample"])  # infinite values stop the run (registry/errors.yaml)

# %% Design
y = "value"
r = bf.prior_scale("t", "medium", 0.707)
alternative = "two-sided"
mu = 0
cred = 0.95
design = "two-sample"
g = "sample"
levels = list(df[g].cat.categories)
if len(levels) != 2:
    cs.cs_error("CS_E_GROUP_COUNT", column=g, expected=2, k=len(levels))
x1 = df.loc[df[g] == levels[0], y].to_numpy(dtype=float)
x2 = df.loc[df[g] == levels[1], y].to_numpy(dtype=float)
for lvl, v in zip(levels, (x1, x2)):  # the pooled SD needs two values per group
    if len(v) < 2:
        cs.cs_error("CS_E_SMALL_GROUP", min=2, group=f"{g} = {lvl}", n=len(v))
if len(np.unique(df[y].to_numpy(dtype=float))) < 2:  # no variation: t is 0/0
    cs.cs_error("CS_E_CONSTANT", column=y)
res = bf.ttest_bf(x1, x2, mu=mu, r=r, alternative=alternative, cred=cred,
                  robustness=True, sequential=True,
                  seq_values=df[y].to_numpy(dtype=float), seq_labels=(df[g] == levels[1]).to_numpy().astype(int))
n1, n2 = len(x1), len(x2)
mean_diff = float(x1.mean() - x2.mean())
groups = [(str(levels[0]), x1), (str(levels[1]), x2)]
effect_text = f"{levels[0]} − {levels[1]}"
n = int(sum(len(v) for _, v in groups)) if design == "two-sample" else int(n1)
bf10 = res["bf10"]
post = res["post"]

# %% Assumptions (the t likelihood: normal data; two groups: one common variance)
assumptions = []
bad = [lv for lv, v in groups if 3 <= len(v) <= 5000 and stats.shapiro(v).pvalue < 0.05]
small = min(len(v) for _, v in groups) < 30
if any(not (3 <= len(v) <= 5000) for _, v in groups):
    status, detail = "info", "Too few (or too many) values for Shapiro–Wilk; inspect the distribution."
elif bad and small:
    status, detail = "warn", f"Shapiro–Wilk p < .05 for {', '.join(bad)} with fewer than 30 values; the normal likelihood may misstate the evidence."
elif bad:
    status, detail = "info", f"Shapiro–Wilk p < .05 for {', '.join(bad)}, but with 30 or more values the t likelihood is robust."
else:
    status, detail = "pass", "Shapiro–Wilk p ≥ .05."
assumptions.append({"key": "normality", "label": "Normality", "status": status, "detail": detail})
if design == "two-sample":
    dev = [np.abs(v - np.median(v)) for _, v in groups]  # Brown–Forsythe: one-way ANOVA on |x − median|
    grand = np.concatenate(dev).mean()
    ssb = sum(len(d) * (d.mean() - grand) ** 2 for d in dev)
    ssw = sum(((d - d.mean()) ** 2).sum() for d in dev)
    bf_f = (ssb / 1) / (ssw / (n - 2)) if ssw > 0 else math.inf
    bf_p = float(stats.f.sf(bf_f, 1, n - 2))
    ratio = max(groups[0][1].var(ddof=1), groups[1][1].var(ddof=1)) / max(min(groups[0][1].var(ddof=1), groups[1][1].var(ddof=1)), 1e-300)
    status = "warn" if bf_p < 0.05 and ratio > 2 else "info" if bf_p < 0.05 else "pass"
    assumptions.append({"key": "equal_variance", "label": "Equal variances", "status": status,
                        "detail": f"Brown–Forsythe F = {bf_f:.2f}, {cs.fmt_p(bf_p)}; variance ratio {ratio:.2f}. The JZS model has one common variance.",
                        "statistic": float(bf_f), "p": bf_p})
assumptions.append({"key": "independence", "label": "Independent observations", "status": "info",
                    "detail": "Each row should be a separate subject (pairs share a row)."})

# %% Result
label = bf.evidence_label(bf10)
direction = {"two-sided": "δ ≠ 0", "greater": "δ > 0", "less": "δ < 0"}[alternative]
summary = (
    f"BF₁₀ = {cs.fmt_num(bf10)}: the data are {cs.fmt_num(bf10 if bf10 >= 1 else 1 / bf10)} times more likely under "
    f"{'the alternative (' + direction + ')' if bf10 >= 1 else 'the null (δ = 0)'} than under {'the null' if bf10 >= 1 else 'the alternative'} — {label} "
    f"(Cauchy prior on δ, r = {r:.3g}). Under the alternative, δ is most likely near {post['median']:.2f} "
    f"({cred:.0%} credible interval [{post['low']:.2f}, {post['high']:.2f}])."
)
prior_odds_note = f"With equal prior odds, P(H₁ | data) = {bf10 / (1 + bf10):.3f}."
desc = [{"group": lv, "n": len(v), "mean": float(v.mean()), "sd": float(v.std(ddof=1)) if len(v) > 1 else None} for lv, v in groups]
grid = res["grid"]
charts = [cs.chart(
    "prior_posterior", "prior-posterior", "Prior and posterior of δ",
    {"x": cs.col("δ (standardized effect)", np.concatenate([grid, grid])),
     "density": cs.col("density", np.concatenate([res["prior_density"], res["posterior_density"]])),
     "curve": cs.col("curve", ["Prior"] * len(grid) + ["Posterior"] * len(grid), levels=["Prior", "Posterior"])},
    controls={"point": 0, "ci_low": post["low"], "ci_high": post["high"], "cred": cred, "bf10": bf10},
)]
if "robust_r" in res:
    charts.append(cs.chart("robustness", "bf-robustness", "Bayes factor across prior widths",
                           {"x": cs.col("prior width r", res["robust_r"]), "bf": cs.col("BF₁₀", res["robust_bf"])}, controls={"chosen": r}))
if "seq_n" in res and len(res["seq_n"]) >= 2:
    charts.append(cs.chart("sequential", "bf-sequential", "Bayes factor as rows accumulate",
                           {"n": cs.col("rows", res["seq_n"]), "bf": cs.col("BF₁₀", res["seq_bf"])}))
cs.publish({
    "method": "bayes.ttest",
    "methodVersion": "1.0.1",
    "title": {"two-sample": "Bayesian two-sample t-test", "paired": "Bayesian paired t-test", "one-sample": "Bayesian one-sample t-test"}[design],
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"BF₁₀ = {cs.fmt_num(bf10)} (JZS, r = {r:.3g}), δ = {post['median']:.2f}, {cred:.0%} CrI [{post['low']:.2f}, {post['high']:.2f}]",
    "statistics": [
        {"key": "bf10", "label": f"BF₁₀ ({direction} vs δ = 0)", "value": bf10},
        {"key": "bf01", "label": "BF₀₁", "value": 1 / bf10},
        {"key": "delta", "label": "δ (posterior median)", "value": post["median"]},
        {"key": "cri", "label": f"{cred:.0%} credible interval", "value": [post["low"], post["high"]]},
        {"key": "t", "label": "t", "value": res["t"]},
        {"key": "df", "label": "df", "value": res["df"]},
    ],
    "tables": [
        {"key": "descriptives", "title": "Descriptives",
         "columns": [{"key": "group", "label": "Sample", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
                     {"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"}],
         "rows": desc},
        {"key": "evidence", "title": "Evidence",
         "columns": [{"key": "quantity", "label": "Quantity", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
         "rows": [{"quantity": "BF₁₀ (chosen alternative)", "value": bf10},
                  {"quantity": "BF₁₀ (two-sided)", "value": res["bf10_two_sided"]},
                  {"quantity": "P(H₁ | data), equal prior odds", "value": bf10 / (1 + bf10)},
                  {"quantity": "Posterior mean of δ", "value": post["mean"]},
                  {"quantity": "Numerical error of BF (%)", "value": 100 * res["error"]}]},
    ],
    "effectSizes": [
        {"key": "delta", "label": "δ (posterior median)", "value": post["median"], "ciLow": post["low"], "ciHigh": post["high"], "ciLevel": cred,
         "method": "posterior under H₁ (JZS), equal-tailed credible interval"},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [
        f"Effect: {effect_text}; prior δ ~ Cauchy(0, {r:.3g}){'' if alternative == 'two-sided' else ', restricted to ' + direction}.",
        f"Evidence: {label}. {prior_odds_note}",
        "A Bayes factor compares how well two hypotheses predicted the data; it is not a p-value and is not entered in the multiple-testing ledger.",
    ],
    "values": {
        "bf10": bf10, "bf01": 1 / bf10, "log_bf10": res["log_bf10"], "bf10_two_sided": res["bf10_two_sided"], "p_h1": bf10 / (1 + bf10),
        "t": res["t"], "df": res["df"], "n_eff": res["n_eff"], "r": r,
        "delta_mean": post["mean"], "delta_median": post["median"], "delta_low": post["low"], "delta_high": post["high"],
        "n": n, "n_1": n1, "n_2": n2, "mean_diff": mean_diff, "error_pct": 100 * res["error"],
        "bf_robust_min": float(np.min(res["robust_bf"])) if "robust_bf" in res else None,
        "bf_robust_max": float(np.max(res["robust_bf"])) if "robust_bf" in res else None, "design": design,
    },
    "charts": charts,
})
R

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

# Bayesian t-test (JZS Bayes factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.ttest 1.0.1 · spec dbff3bb54fdc088d
# Dataset: a_xy_long (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_bayes_ttest, cs_bayes_prior_scale, cs_bayes_evidence_label (twins of codesplash.stats.bayes)

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

# %% Design
y <- "value"
r <- cs_bayes_prior_scale("t", "medium", 0.707)
alternative <- "two-sided"
mu <- 0
cred <- 0.95
design <- "two-sample"
g <- "sample"
levels_g <- levels(df[[g]])
if (length(levels_g) != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = length(levels_g))
x1 <- as.numeric(df[[y]][df[[g]] == levels_g[1]])
x2 <- as.numeric(df[[y]][df[[g]] == levels_g[2]])
for (i in 1:2) {  # the pooled SD needs two values per group
  n_i <- length(list(x1, x2)[[i]])
  if (n_i < 2) cs_error("CS_E_SMALL_GROUP", min = 2, group = paste0(g, " = ", levels_g[i]), n = n_i)
}
if (length(unique(as.numeric(df[[y]]))) < 2) cs_error("CS_E_CONSTANT", column = y)  # no variation: t is 0/0
res <- cs_bayes_ttest(x1, x2, mu = mu, r = r, alternative = alternative, cred = cred,
                      robustness = TRUE, sequential = TRUE,
                      seq_values = as.numeric(df[[y]]), seq_labels = as.integer(df[[g]] == levels_g[2]))
n1 <- length(x1)
n2 <- length(x2)
mean_diff <- mean(x1) - mean(x2)
groups <- list(list(name = levels_g[1], v = x1), list(name = levels_g[2], v = x2))
effect_text <- sprintf("%s − %s", levels_g[1], levels_g[2])
n <- if (design == "two-sample") n1 + n2 else n1
bf10 <- res$bf10
post <- res$post

# %% Assumptions
assumptions <- list()
sizes <- vapply(groups, function(gr) length(gr$v), numeric(1))
bad <- character(0)
for (gr in groups) if (length(gr$v) >= 3 && length(gr$v) <= 5000 && stats::shapiro.test(gr$v)$p.value < 0.05) bad <- c(bad, gr$name)
if (any(sizes < 3 | sizes > 5000)) {
  status <- "info"
  detail <- "Too few (or too many) values for Shapiro–Wilk; inspect the distribution."
} else if (length(bad) && min(sizes) < 30) {
  status <- "warn"
  detail <- sprintf("Shapiro–Wilk p < .05 for %s with fewer than 30 values; the normal likelihood may misstate the evidence.", paste(bad, collapse = ", "))
} else if (length(bad)) {
  status <- "info"
  detail <- sprintf("Shapiro–Wilk p < .05 for %s, but with 30 or more values the t likelihood is robust.", paste(bad, collapse = ", "))
} else {
  status <- "pass"
  detail <- "Shapiro–Wilk p ≥ .05."
}
assumptions[[length(assumptions) + 1]] <- list(key = "normality", label = "Normality", status = status, detail = detail)
if (design == "two-sample") {
  dev <- lapply(groups, function(gr) abs(gr$v - stats::median(gr$v)))
  grand <- mean(unlist(dev))
  ssb <- sum(vapply(dev, function(d) length(d) * (mean(d) - grand)^2, numeric(1)))
  ssw <- sum(vapply(dev, function(d) sum((d - mean(d))^2), numeric(1)))
  bf_f <- if (ssw > 0) (ssb / 1) / (ssw / (n - 2)) else Inf
  bf_p <- stats::pf(bf_f, 1, n - 2, lower.tail = FALSE)
  vars <- vapply(groups, function(gr) stats::var(gr$v), numeric(1))
  ratio <- max(vars) / max(min(vars), 1e-300)
  status <- if (bf_p < 0.05 && ratio > 2) "warn" else if (bf_p < 0.05) "info" else "pass"
  assumptions[[length(assumptions) + 1]] <- list(key = "equal_variance", label = "Equal variances", status = status,
    detail = sprintf("Brown–Forsythe F = %.2f, %s; variance ratio %.2f. The JZS model has one common variance.", bf_f, cs_fmt_p(bf_p), ratio),
    statistic = bf_f, p = bf_p)
}
assumptions[[length(assumptions) + 1]] <- list(key = "independence", label = "Independent observations", status = "info",
  detail = "Each row should be a separate subject (pairs share a row).")

# %% Result
label <- cs_bayes_evidence_label(bf10)
direction <- switch(alternative, "two-sided" = "δ ≠ 0", greater = "δ > 0", less = "δ < 0")
summary <- sprintf(
  "BF₁₀ = %s: the data are %s times more likely under %s than under %s — %s (Cauchy prior on δ, r = %s). Under the alternative, δ is most likely near %.2f (%s credible interval [%.2f, %.2f]).",
  cs_fmt_num(bf10), cs_fmt_num(if (bf10 >= 1) bf10 else 1 / bf10),
  if (bf10 >= 1) sprintf("the alternative (%s)", direction) else "the null (δ = 0)",
  if (bf10 >= 1) "the null" else "the alternative", label, format(signif(r, 3)),
  post$median, sprintf("%.0f%%", 100 * cred), post$low, post$high)
desc <- lapply(groups, function(gr) list(group = gr$name, n = length(gr$v), mean = mean(gr$v), sd = if (length(gr$v) > 1) stats::sd(gr$v) else NULL))
grid <- res$grid
charts <- list(cs_chart("prior_posterior", "prior-posterior", "Prior and posterior of δ",
  list(x = cs_col("δ (standardized effect)", c(grid, grid)),
       density = cs_col("density", c(res$prior_density, res$posterior_density)),
       curve = cs_col("curve", c(rep("Prior", length(grid)), rep("Posterior", length(grid))), levels = c("Prior", "Posterior"))),
  controls = list(point = 0, ci_low = post$low, ci_high = post$high, cred = cred, bf10 = bf10)))
if (!is.null(res$robust_r)) {
  charts[[length(charts) + 1]] <- cs_chart("robustness", "bf-robustness", "Bayes factor across prior widths",
    list(x = cs_col("prior width r", res$robust_r), bf = cs_col("BF₁₀", res$robust_bf)), controls = list(chosen = r))
}
if (!is.null(res$seq_n) && length(res$seq_n) >= 2) {
  charts[[length(charts) + 1]] <- cs_chart("sequential", "bf-sequential", "Bayes factor as rows accumulate",
    list(n = cs_col("rows", as.numeric(res$seq_n)), bf = cs_col("BF₁₀", res$seq_bf)))
}
cs_publish(list(
  method = "bayes.ttest",
  methodVersion = "1.0.1",
  title = switch(design, "two-sample" = "Bayesian two-sample t-test", paired = "Bayesian paired t-test", "one-sample" = "Bayesian one-sample t-test"),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("BF₁₀ = %s (JZS, r = %s), δ = %.2f, %s CrI [%.2f, %.2f]", cs_fmt_num(bf10), format(signif(r, 3)), post$median,
                sprintf("%.0f%%", 100 * cred), post$low, post$high),
  statistics = list(
    list(key = "bf10", label = sprintf("BF₁₀ (%s vs δ = 0)", direction), value = bf10),
    list(key = "bf01", label = "BF₀₁", value = 1 / bf10),
    list(key = "delta", label = "δ (posterior median)", value = post$median),
    list(key = "cri", label = sprintf("%.0f%% credible interval", 100 * cred), value = c(post$low, post$high)),
    list(key = "t", label = "t", value = res$t),
    list(key = "df", label = "df", value = res$df)
  ),
  tables = list(
    list(key = "descriptives", title = "Descriptives",
         columns = list(list(key = "group", label = "Sample", type = "string"), list(key = "n", label = "n", type = "integer"),
                        list(key = "mean", label = "Mean", type = "number"), list(key = "sd", label = "SD", type = "number")),
         rows = desc),
    list(key = "evidence", title = "Evidence",
         columns = list(list(key = "quantity", label = "Quantity", type = "string"), list(key = "value", label = "Value", type = "number")),
         rows = list(list(quantity = "BF₁₀ (chosen alternative)", value = bf10),
                     list(quantity = "BF₁₀ (two-sided)", value = res$bf10_two_sided),
                     list(quantity = "P(H₁ | data), equal prior odds", value = bf10 / (1 + bf10)),
                     list(quantity = "Posterior mean of δ", value = post$mean),
                     list(quantity = "Numerical error of BF (%)", value = 100 * res$error)))
  ),
  effectSizes = list(list(key = "delta", label = "δ (posterior median)", value = post$median, ciLow = post$low, ciHigh = post$high, ciLevel = cred,
                          method = "posterior under H₁ (JZS), equal-tailed credible interval")),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(
    sprintf("Effect: %s; prior δ ~ Cauchy(0, %s)%s.", effect_text, format(signif(r, 3)), if (alternative == "two-sided") "" else paste0(", restricted to ", direction)),
    sprintf("Evidence: %s. With equal prior odds, P(H₁ | data) = %.3f.", label, bf10 / (1 + bf10)),
    "A Bayes factor compares how well two hypotheses predicted the data; it is not a p-value and is not entered in the multiple-testing ledger."
  ),
  values = list(
    bf10 = bf10, bf01 = 1 / bf10, log_bf10 = res$log_bf10, bf10_two_sided = res$bf10_two_sided, p_h1 = bf10 / (1 + bf10),
    t = res$t, df = res$df, n_eff = res$n_eff, r = r,
    delta_mean = post$mean, delta_median = post$median, delta_low = post$low, delta_high = post$high,
    n = n, n_1 = n1, n_2 = n2, mean_diff = mean_diff, error_pct = 100 * res$error,
    bf_robust_min = if (!is.null(res$robust_bf)) min(res$robust_bf) else NULL,
    bf_robust_max = if (!is.null(res$robust_bf)) max(res$robust_bf) else NULL, design = design
  ),
  charts = charts
))

Sources

  • Rouder, J. N., Speckman, P. L., Sun, D., Morey, R. D., & Iverson, G. (2009). Bayesian t tests for accepting and rejecting the null hypothesis. Psychonomic Bulletin & Review, 16, 225–237.
  • Wagenmakers, E.-J., Lodewyckx, T., Kuriyal, H., & Grasman, R. (2010). Bayesian hypothesis testing for psychologists: a tutorial on the Savage–Dickey method. Cognitive Psychology, 60, 158–189.
  • Lee, M. D., & Wagenmakers, E.-J. (2013). Bayesian cognitive modeling: a practical course. Cambridge University Press.

From the CodeSplash method registry · bayes.ttest v1.0.1.