BBayesian · bayes.correlation
Bayesian correlation (Jeffreys Bayes factor)
How much more likely are the data if two variables are correlated than if they are not?
Jeffreys' Bayes factor for a Pearson correlation ρ against ρ = 0, with a stretched-beta prior of width κ on ρ (exact likelihood, Ly, Verhagen & Wagenmakers 2016). Reports the posterior of ρ with a credible interval, the Bayes factor across prior widths, and how it grew as rows accumulated.
A real result
Example “Guide uniform”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
BF₁₀ = 1.21 (κ = 1), r = .54, ρ = 0.44, 95% CrI [-0.17, 0.80]
- BF₁₀ (ρ ≠ 0 vs ρ = 0)
- 1.209
- BF₀₁
- 0.8270
- Sample r
- 0.5375
- ρ (posterior median)
- 0.4386
- 95% credible interval
- [−0.1674, 0.8028]
Effect size
- ρ (posterior median) 0.4386 95% CI [−0.1674, 0.8028]
Plots
View data
| curve | density | ρ |
|---|---|---|
| Prior | 0.5000 | −1.0000 |
| Prior | 0.5000 | −0.9900 |
| Prior | 0.5000 | −0.9800 |
| Prior | 0.5000 | −0.9700 |
| Prior | 0.5000 | −0.9600 |
| Prior | 0.5000 | −0.9500 |
| Prior | 0.5000 | −0.9400 |
| Prior | 0.5000 | −0.9300 |
| Prior | 0.5000 | −0.9200 |
| Prior | 0.5000 | −0.9100 |
| Prior | 0.5000 | −0.9000 |
| Prior | 0.5000 | −0.8900 |
| Prior | 0.5000 | −0.8800 |
| Prior | 0.5000 | −0.8700 |
| Prior | 0.5000 | −0.8600 |
| Prior | 0.5000 | −0.8500 |
| Prior | 0.5000 | −0.8400 |
| Prior | 0.5000 | −0.8300 |
| Prior | 0.5000 | −0.8200 |
| Prior | 0.5000 | −0.8100 |
| Prior | 0.5000 | −0.8000 |
| Prior | 0.5000 | −0.7900 |
| Prior | 0.5000 | −0.7800 |
| Prior | 0.5000 | −0.7700 |
| Prior | 0.5000 | −0.7600 |
| Prior | 0.5000 | −0.7500 |
| Prior | 0.5000 | −0.7400 |
| Prior | 0.5000 | −0.7300 |
| Prior | 0.5000 | −0.7200 |
| Prior | 0.5000 | −0.7100 |
| Prior | 0.5000 | −0.7000 |
| Prior | 0.5000 | −0.6900 |
| Prior | 0.5000 | −0.6800 |
| Prior | 0.5000 | −0.6700 |
| Prior | 0.5000 | −0.6600 |
| Prior | 0.5000 | −0.6500 |
| Prior | 0.5000 | −0.6400 |
| Prior | 0.5000 | −0.6300 |
| Prior | 0.5000 | −0.6200 |
| Prior | 0.5000 | −0.6100 |
| Prior | 0.5000 | −0.6000 |
| Prior | 0.5000 | −0.5900 |
| Prior | 0.5000 | −0.5800 |
| Prior | 0.5000 | −0.5700 |
| Prior | 0.5000 | −0.5600 |
| Prior | 0.5000 | −0.5500 |
| Prior | 0.5000 | −0.5400 |
| Prior | 0.5000 | −0.5300 |
| Prior | 0.5000 | −0.5200 |
| Prior | 0.5000 | −0.5100 |
| Prior | 0.5000 | −0.5000 |
| Prior | 0.5000 | −0.4900 |
| Prior | 0.5000 | −0.4800 |
| Prior | 0.5000 | −0.4700 |
| Prior | 0.5000 | −0.4600 |
| Prior | 0.5000 | −0.4500 |
| Prior | 0.5000 | −0.4400 |
| Prior | 0.5000 | −0.4300 |
| Prior | 0.5000 | −0.4200 |
| Prior | 0.5000 | −0.4100 |
First 60 of 402 rows.
View data
| BF₁₀ | prior width κ |
|---|---|
| 1.155 | 0.0500 |
| 1.168 | 0.0549 |
| 1.181 | 0.0603 |
| 1.196 | 0.0662 |
| 1.210 | 0.0727 |
| 1.226 | 0.0798 |
| 1.242 | 0.0877 |
| 1.258 | 0.0963 |
| 1.275 | 0.1057 |
| 1.292 | 0.1161 |
| 1.309 | 0.1275 |
| 1.326 | 0.1400 |
| 1.343 | 0.1538 |
| 1.359 | 0.1689 |
| 1.373 | 0.1854 |
| 1.387 | 0.2036 |
| 1.399 | 0.2236 |
| 1.409 | 0.2456 |
| 1.417 | 0.2696 |
| 1.423 | 0.2961 |
| 1.426 | 0.3252 |
| 1.426 | 0.3333 |
| 1.426 | 0.3571 |
| 1.423 | 0.3921 |
| 1.416 | 0.4306 |
| 1.406 | 0.4729 |
| 1.393 | 0.5193 |
| 1.376 | 0.5702 |
| 1.374 | 0.5774 |
| 1.356 | 0.6262 |
| 1.333 | 0.6877 |
| 1.306 | 0.7551 |
| 1.276 | 0.8293 |
| 1.244 | 0.9106 |
| 1.209 | 1 |
View data
| BF₁₀ | rows |
|---|---|
| 1.360 | 3 |
| 0.8554 | 4 |
| 1.345 | 5 |
| 0.7635 | 6 |
| 0.7483 | 7 |
| 0.7452 | 8 |
| 1.373 | 9 |
| 1.209 | 10 |
View data
| x | y |
|---|---|
| 4.200 | 4 |
| 5.100 | 4.400 |
| 5.400 | 4.800 |
| 4.800 | 5 |
| 6 | 5.100 |
| 5.800 | 4.300 |
| 4.900 | 4.700 |
| 5.600 | 4.600 |
| 6.200 | 5.200 |
| 5 | 4.900 |
Assumptions
- Bivariate normality — No extreme rows; marginal distributions are compatible with normality or n ≥ 30.
- Linear relationship — Check the scatter plot: ρ measures linear association.
- Independent observations — Each row should be a separate unit.
Evidence
| Quantity | Value |
|---|---|
| BF₁₀ (chosen alternative) | 1.209 |
| BF₁₀ (two-sided) | 1.209 |
| P(H₁ | data), equal prior odds | 0.5473 |
| Posterior mean of ρ | 0.4060 |
- Prior: ρ ~ stretched Beta(1/κ, 1/κ) on (−1, 1), κ = 1.
- Evidence: anecdotal evidence for H₁. With equal prior odds, P(H₁ | data) = 0.547.
- A Bayes factor is relative evidence, not a p-value; it is not entered in the multiple-testing ledger.
BF₁₀ = 1.21 (κ = 1), r = .54, ρ = 0.44, 95% CrI [-0.17, 0.80]
- BF₁₀ (ρ ≠ 0 vs ρ = 0)
- 1.209
- BF₀₁
- 0.8270
- Sample r
- 0.5375
- ρ (posterior median)
- 0.4386
- 95% credible interval
- [−0.1674, 0.8028]
Effect size
- ρ (posterior median) 0.4386 95% CI [−0.1674, 0.8028]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Bivariate normality — No extreme rows; marginal distributions are compatible with normality or n ≥ 30.
- Linear relationship — Check the scatter plot: ρ measures linear association.
- Independent observations — Each row should be a separate unit.
Evidence
| Quantity | Value |
|---|---|
| BF₁₀ (chosen alternative) | 1.209 |
| BF₁₀ (two-sided) | 1.209 |
| P(H₁ | data), equal prior odds | 0.5473 |
| Posterior mean of ρ | 0.4060 |
- Prior: ρ ~ stretched Beta(1/κ, 1/κ) on (−1, 1), κ = 1.
- Evidence: anecdotal evidence for H₁. With equal prior odds, P(H₁ | data) = 0.547.
- A Bayes factor is relative evidence, not a p-value; it 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 uniforma_xy_wide · x: x · y: y
- Guide medium greatera_xy_wide · x: x · y: y
- Airquality wideairquality · x: Wind · y: Temp
- Degenerate constanta_xy_wide · x: x · y: y
- Degenerate n2a_xy_wide · x: x · y: y
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Continuous–continuous: Pearson / Spearman / Kendall · Statistics Guide · C — Test association
What you need
- First variablenumeric · 1 column
- One numeric variable.
- Second variablenumeric · 1 column
- The other numeric variable (same rows).
Choices you make
hypothesis
- Prior width on ρdefault medium
The stretched-beta prior width κ; larger κ spreads belief over stronger correlations.
- Medium (κ = 1/3)(default) — Beta(3, 3) on ρ: moderate correlations expected (BayesFactor's default).
- Wide (κ = 1/√3 ≈ 0.58) — Beta(√3, √3): broader.
- Ultrawide (κ = 1, uniform) — Every ρ in (−1, 1) equally likely a priori (Jeffreys).
- Custom — Any κ in (0, 1]: the prior is a Beta(1/κ, 1/κ) stretched to (−1, 1).
- Prior width κdefault 0.333
Width of the stretched-beta prior on ρ (1 = uniform).
- Alternative hypothesisdefault two-sided
Directional hypotheses put the whole prior on one side of zero.
- ρ ≠ 0(default) — Either sign.
- ρ > 0 — Positive correlation only.
- ρ < 0 — Negative correlation only.
- Credible leveldefault 0.95
Equal-tailed posterior interval for ρ under H₁.
Advanced
- Robustness across prior widthsdefault on
Recompute the Bayes factor for κ from 0.05 to 1 (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.
Linear relationship
Pearson's ρ measures linear association; check the scatter plot.
Bivariate normality
The likelihood assumes bivariate normal data; outliers can dominate.
- If violated → Kendall's τ (frequentist) — Rank-based; resists outliers and skew that distort Pearson's ρ and its Bayes factor. Changes the question: Measures monotonic association (concordance) with a p-value instead of a Bayes factor for ρ.
Independent observations
Each row is a separate unit.
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.
- r
- A number from −1 to 1 for how closely two variables move together; Pearson measures straight-line association.
- n
- How many independent units the analysis used; it sets precision and power.
- kappa
- Agreement between raters beyond what chance would produce; 0 is chance level, 1 is perfect.
- rho_mean
- Your belief about a parameter after combining the prior with the data.
- rho_median
- Your belief about a parameter after combining the prior with the data.
- rho_low
- A range of effect values compatible with your data at the chosen confidence level.
- rho_high
- A range of effect values compatible with your data at the chosen confidence level.
- error_pct
- Estimated error of the numerical integration behind the Bayes factor, in percent of its value (ANOVA: the largest over models).
- 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
- One-sided Bayes factors use Jeffreys' exact likelihood (so BF₊₀ + BF₋₀ = 2·BF₁₀). BayesFactor::correlationBF's interval Bayes factors use the approximate likelihood (1 − ρ²)^((n−1)/2)(1 − ρr)^(−(2n−3)/2) and differ by ≈0.1–0.5% at small n; the two-sided Bayes factors agree to 1e-10.
- Posterior summaries are exact numerical quantiles; BayesFactor's posterior() samples by MCMC.
The exact script CodeSplash ran for example “Guide uniform” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Bayesian correlation (Jeffreys Bayes factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.correlation 1.0.1 · spec 826421b779817164
# Dataset: a_xy_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 stats
import codesplash as cs
from codesplash.stats import bayes as bf # Jeffreys correlation Bayes factor (twin of R cs_bayes_*)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/a_xy_wide.parquet", columns=["x", "y"])
n_input = len(df)
df = df.dropna(subset=["x", "y"]) # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["x", "y"]) # infinite values stop the run (registry/errors.yaml)
# %% Test
a, b = "x", "y"
x = df[a].to_numpy(dtype=float)
y = df[b].to_numpy(dtype=float)
if len(x) < 3:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A Bayesian correlation", min=3, n=len(x))
for column, v in ((a, x), (b, y)): # exact check: a float SD of identical values need not be 0
if len(np.unique(v)) < 2:
cs.cs_error("CS_E_CONSTANT", column=column)
kappa = bf.prior_scale("correlation", "ultrawide", 0.333)
alternative = "two-sided"
cred = 0.95
res = bf.corr_bf(x, y, kappa=kappa, alternative=alternative, cred=cred,
robustness=True, sequential=True)
bf10 = res["bf10"]
post = res["post"]
n = len(x)
# %% Assumptions
assumptions = []
sw = [stats.shapiro(v).pvalue if 3 <= len(v) <= 5000 else None for v in (x, y)]
z = np.abs(stats.zscore(x)), np.abs(stats.zscore(y))
extreme = int(((z[0] > 3.5) | (z[1] > 3.5)).sum())
if extreme:
status, detail = "warn", f"{extreme} row(s) lie more than 3.5 SD from a mean; Pearson's r and its Bayes factor can hinge on them."
elif any(p is not None and p < 0.05 for p in sw) and n < 30:
status, detail = "warn", "Shapiro–Wilk p < .05 for a variable with fewer than 30 rows; the bivariate-normal likelihood is doubtful."
else:
status, detail = "pass", "No extreme rows; marginal distributions are compatible with normality or n ≥ 30."
assumptions.append({"key": "normality", "label": "Bivariate normality", "status": status, "detail": detail})
assumptions.append({"key": "linearity", "label": "Linear relationship", "status": "info", "detail": "Check the scatter plot: ρ measures linear association."})
assumptions.append({"key": "independence", "label": "Independent observations", "status": "info", "detail": "Each row should be a separate unit."})
# %% Result
label = bf.evidence_label(bf10)
direction = {"two-sided": "ρ ≠ 0", "greater": "ρ > 0", "less": "ρ < 0"}[alternative]
summary = (
f"BF₁₀ = {cs.fmt_num(bf10)} for a correlation between {a} and {b} (sample r = {res['r']:.2f}, n = {n}): "
f"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 'no correlation'} — {label} (prior width κ = {kappa:.3g}). "
f"Under the alternative, ρ is most likely near {post['median']:.2f} ({cred:.0%} credible interval [{post['low']:.2f}, {post['high']:.2f}])."
)
grid = res["grid"]
charts = [cs.chart(
"prior_posterior", "prior-posterior", "Prior and posterior of ρ",
{"x": cs.col("ρ", 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 κ", res["robust_r"]), "bf": cs.col("BF₁₀", res["robust_bf"])}, controls={"chosen": kappa}))
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"])}))
rows = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int))
charts.append(cs.chart("scatter", "scatter", f"{b} against {a}", {"x": cs.col(a, x[rows]), "y": cs.col(b, y[rows])}))
cs.publish({
"method": "bayes.correlation",
"methodVersion": "1.0.1",
"title": "Bayesian correlation",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"BF₁₀ = {cs.fmt_num(bf10)} (κ = {kappa:.3g}), r = {cs.fmt_num(res['r'], leading_zero=False)}, ρ = {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": "r", "label": "Sample r", "value": res["r"]},
{"key": "rho", "label": "ρ (posterior median)", "value": post["median"]},
{"key": "cri", "label": f"{cred:.0%} credible interval", "value": [post["low"], post["high"]]},
],
"tables": [{"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"]}]}],
"effectSizes": [{"key": "rho", "label": "ρ (posterior median)", "value": post["median"], "ciLow": post["low"], "ciHigh": post["high"], "ciLevel": cred,
"method": "posterior under H₁ (Jeffreys exact likelihood), equal-tailed credible interval"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Prior: ρ ~ stretched Beta(1/κ, 1/κ) on (−1, 1), κ = {kappa:.3g}{'' if alternative == 'two-sided' else ', restricted to ' + direction}.",
f"Evidence: {label}. With equal prior odds, P(H₁ | data) = {bf10 / (1 + bf10):.3f}.",
"A Bayes factor is relative evidence, not a p-value; it 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),
"r": res["r"], "n": n, "kappa": kappa, "rho_mean": post["mean"], "rho_median": post["median"],
"rho_low": post["low"], "rho_high": post["high"], "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,
},
"charts": charts,
})
The exact script CodeSplash ran for example “Guide uniform” · R version 4.5.1 (2025-06-13)
# Bayesian correlation (Jeffreys Bayes factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.correlation 1.0.1 · spec 826421b779817164
# Dataset: a_xy_wide (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_corr, 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_wide.parquet", col_select = c("x", "y")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x", "y")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("x", "y")) # infinite values stop the run (registry/errors.yaml)
# %% Test
a <- "x"
b <- "y"
x <- as.numeric(df[[a]])
y <- as.numeric(df[[b]])
if (length(x) < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "A Bayesian correlation", min = 3, n = length(x))
if (length(unique(x)) < 2) cs_error("CS_E_CONSTANT", column = a)
if (length(unique(y)) < 2) cs_error("CS_E_CONSTANT", column = b)
kappa <- cs_bayes_prior_scale("correlation", "ultrawide", 0.333)
alternative <- "two-sided"
cred <- 0.95
res <- cs_bayes_corr(x, y, kappa = kappa, alternative = alternative, cred = cred,
robustness = TRUE, sequential = TRUE)
bf10 <- res$bf10
post <- res$post
n <- length(x)
# %% Assumptions
assumptions <- list()
sw <- vapply(list(x, y), function(v) if (length(v) >= 3 && length(v) <= 5000) stats::shapiro.test(v)$p.value else NA_real_, numeric(1))
zs <- function(v) abs((v - mean(v)) / stats::sd(v) * sqrt(length(v) / (length(v) - 1)))
extreme <- sum(zs(x) > 3.5 | zs(y) > 3.5)
if (extreme > 0) {
status <- "warn"
detail <- sprintf("%d row(s) lie more than 3.5 SD from a mean; Pearson's r and its Bayes factor can hinge on them.", extreme)
} else if (any(!is.na(sw) & sw < 0.05) && n < 30) {
status <- "warn"
detail <- "Shapiro–Wilk p < .05 for a variable with fewer than 30 rows; the bivariate-normal likelihood is doubtful."
} else {
status <- "pass"
detail <- "No extreme rows; marginal distributions are compatible with normality or n ≥ 30."
}
assumptions[[length(assumptions) + 1]] <- list(key = "normality", label = "Bivariate normality", status = status, detail = detail)
assumptions[[length(assumptions) + 1]] <- list(key = "linearity", label = "Linear relationship", status = "info", detail = "Check the scatter plot: ρ measures linear association.")
assumptions[[length(assumptions) + 1]] <- list(key = "independence", label = "Independent observations", status = "info", detail = "Each row should be a separate unit.")
# %% Result
label <- cs_bayes_evidence_label(bf10)
direction <- switch(alternative, "two-sided" = "ρ ≠ 0", greater = "ρ > 0", less = "ρ < 0")
summary <- sprintf(
"BF₁₀ = %s for a correlation between %s and %s (sample r = %.2f, n = %d): the data are %s times more likely under %s — %s (prior width κ = %s). Under the alternative, ρ is most likely near %.2f (%s credible interval [%.2f, %.2f]).",
cs_fmt_num(bf10), a, b, res$r, n, cs_fmt_num(if (bf10 >= 1) bf10 else 1 / bf10),
if (bf10 >= 1) sprintf("the alternative (%s)", direction) else "no correlation", label, format(signif(kappa, 3)),
post$median, sprintf("%.0f%%", 100 * cred), post$low, post$high)
grid <- res$grid
charts <- list(cs_chart("prior_posterior", "prior-posterior", "Prior and posterior of ρ",
list(x = cs_col("ρ", 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 κ", res$robust_r), bf = cs_col("BF₁₀", res$robust_bf)), controls = list(chosen = kappa))
}
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)))
}
rows <- unique(as.integer(round(seq(0, n - 1, length.out = min(n, 5000))))) + 1L
charts[[length(charts) + 1]] <- cs_chart("scatter", "scatter", sprintf("%s against %s", b, a), list(x = cs_col(a, x[rows]), y = cs_col(b, y[rows])))
cs_publish(list(
method = "bayes.correlation",
methodVersion = "1.0.1",
title = "Bayesian correlation",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("BF₁₀ = %s (κ = %s), r = %s, ρ = %.2f, %s CrI [%.2f, %.2f]", cs_fmt_num(bf10), format(signif(kappa, 3)),
cs_fmt_num(res$r, leading_zero = FALSE), 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 = "r", label = "Sample r", value = res$r),
list(key = "rho", label = "ρ (posterior median)", value = post$median),
list(key = "cri", label = sprintf("%.0f%% credible interval", 100 * cred), value = c(post$low, post$high))
),
tables = list(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)))),
effectSizes = list(list(key = "rho", label = "ρ (posterior median)", value = post$median, ciLow = post$low, ciHigh = post$high, ciLevel = cred,
method = "posterior under H₁ (Jeffreys exact likelihood), equal-tailed credible interval")),
assumptions = assumptions,
warnings = warnings,
notes = list(
sprintf("Prior: ρ ~ stretched Beta(1/κ, 1/κ) on (−1, 1), κ = %s%s.", format(signif(kappa, 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 is relative evidence, not a p-value; it 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),
r = res$r, n = n, kappa = kappa, rho_mean = post$mean, rho_median = post$median,
rho_low = post$low, rho_high = post$high, 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
),
charts = charts
))
Sources
- Jeffreys, H. (1961). Theory of Probability (3rd ed.). Oxford University Press.
- Ly, A., Verhagen, J., & Wagenmakers, E.-J. (2016). Harold Jeffreys's default Bayes factor hypothesis tests. Journal of Mathematical Psychology, 72, 19–32.
- Ly, A., Marsman, M., & Wagenmakers, E.-J. (2018). Analytic posteriors for Pearson's correlation coefficient. Statistica Neerlandica, 72, 4–13.
From the CodeSplash method registry · bayes.correlation v1.0.1.