Skip to content

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.

Verified in Python and R Python and R agree to 10 decimals Also called Bayesian correlation, Jeffreys correlation test, correlationBF…

A real result

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

Bayesian correlationRecorded · Python and R agreeRecorded 2026-11-17 · 15 values compared
R

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

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ρ
Prior0.5000−1.0000
Prior0.5000−0.9900
Prior0.5000−0.9800
Prior0.5000−0.9700
Prior0.5000−0.9600
Prior0.5000−0.9500
Prior0.5000−0.9400
Prior0.5000−0.9300
Prior0.5000−0.9200
Prior0.5000−0.9100
Prior0.5000−0.9000
Prior0.5000−0.8900
Prior0.5000−0.8800
Prior0.5000−0.8700
Prior0.5000−0.8600
Prior0.5000−0.8500
Prior0.5000−0.8400
Prior0.5000−0.8300
Prior0.5000−0.8200
Prior0.5000−0.8100
Prior0.5000−0.8000
Prior0.5000−0.7900
Prior0.5000−0.7800
Prior0.5000−0.7700
Prior0.5000−0.7600
Prior0.5000−0.7500
Prior0.5000−0.7400
Prior0.5000−0.7300
Prior0.5000−0.7200
Prior0.5000−0.7100
Prior0.5000−0.7000
Prior0.5000−0.6900
Prior0.5000−0.6800
Prior0.5000−0.6700
Prior0.5000−0.6600
Prior0.5000−0.6500
Prior0.5000−0.6400
Prior0.5000−0.6300
Prior0.5000−0.6200
Prior0.5000−0.6100
Prior0.5000−0.6000
Prior0.5000−0.5900
Prior0.5000−0.5800
Prior0.5000−0.5700
Prior0.5000−0.5600
Prior0.5000−0.5500
Prior0.5000−0.5400
Prior0.5000−0.5300
Prior0.5000−0.5200
Prior0.5000−0.5100
Prior0.5000−0.5000
Prior0.5000−0.4900
Prior0.5000−0.4800
Prior0.5000−0.4700
Prior0.5000−0.4600
Prior0.5000−0.4500
Prior0.5000−0.4400
Prior0.5000−0.4300
Prior0.5000−0.4200
Prior0.5000−0.4100

First 60 of 402 rows.

Bayes factor across prior widthsWould a wider or narrower prior change the conclusion?
View data
BF₁₀prior width κ
1.1550.0500
1.1680.0549
1.1810.0603
1.1960.0662
1.2100.0727
1.2260.0798
1.2420.0877
1.2580.0963
1.2750.1057
1.2920.1161
1.3090.1275
1.3260.1400
1.3430.1538
1.3590.1689
1.3730.1854
1.3870.2036
1.3990.2236
1.4090.2456
1.4170.2696
1.4230.2961
1.4260.3252
1.4260.3333
1.4260.3571
1.4230.3921
1.4160.4306
1.4060.4729
1.3930.5193
1.3760.5702
1.3740.5774
1.3560.6262
1.3330.6877
1.3060.7551
1.2760.8293
1.2440.9106
1.2091
Bayes factor as rows accumulateHow did the evidence grow as the observations came in?
View data
BF₁₀rows
1.3603
0.85544
1.3455
0.76356
0.74837
0.74528
1.3739
1.20910
y against xHow do two numeric variables move together?
View data
xy
4.2004
5.1004.400
5.4004.800
4.8005
65.100
5.8004.300
4.9004.700
5.6004.600
6.2005.200
54.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

QuantityValue
BF₁₀ (chosen alternative)1.209
BF₁₀ (two-sided)1.209
P(H₁ | data), equal prior odds0.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.
Python

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

QuantityValue
BF₁₀ (chosen alternative)1.209
BF₁₀ (two-sided)1.209
P(H₁ | data), equal prior odds0.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.
Python

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,
})
R

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.