Skip to content

CAssociation · correlation.dependence

Test for any dependence (ξ, Hoeffding, distance correlation, HSIC)

Are two variables related in any way, linear or not?

Tests independence against every kind of relationship, not only straight lines: Chatterjee's ξ (how much y is a function of x), Hoeffding's D, distance correlation (dCor) and the Hilbert–Schmidt independence criterion (HSIC) for single variables or sets of variables, and the permutation-free cross HSIC and cross distance-covariance tests. Permutation p-values use a shared seeded stream, so Python and R agree exactly.

Verified in Python and R Python and R agree to 10 decimals Seeded Also called Chatterjee xi, xi correlation, XICOR…

A real result

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

Test of independence: Chatterjee's ξ(x → y)Recorded · Python and R agreeRecorded 2026-11-25 · 22 values compared
R

Chatterjee's ξ(x → y) = 0.402, p < .001, N = 118

Chatterjee's ξ(x → y)
0.4019
z
6.901
p
< .001
n
118

Effect size

  • Chatterjee's ξ(x → y) 0.4019

Plots

y quadratic against xHow do two numeric variables move together?
View data
xy quadratic
0.52060.8319
−1.0800.1154
0.1392−1.026
−0.0847−0.6384
−0.66660.9804
−2.5166.778
−1.0201.064
0.11360.3246
−0.47380.4670
−0.40820.4326
−0.73040.6322
−0.22140.2123
−0.2258−0.6691
−2.5477.544
1.3471.722
0.61640.6260
0.2176−0.6333
−0.80470.4650
0.68970.8538
−0.32870.1813
−0.16470.1581
−1.3921.285
1.4662.395
0.0482−0.2532
1.9082.810
1.7313.307
0.05810.0112
0.64530.0495
1.7263.115
−0.5290−0.6496
0.16641.067
0.33280.2743
0.1824−0.0805
1.1650.7660
0.59350.5174
−0.89180.5918
0.57731.096
−0.82490.1289
−1.1572.008
0.77800.8816
−1.2040.9219
0.3067−0.0010
−0.83370.2404
1.4181.011
0.71181.461
−0.40250.9465
0.79940.7091
0.4265−0.5284
−1.1701.625
−0.2062−0.4512
−0.93061.165
0.44940.6359
−0.64480.5104
−0.23140.0189
−1.2362.067
−0.96101.459
0.13400.2288
−0.99910.9358
−0.14150.4886
0.16730.1283

First 60 of 118 rows.

Assumptions

  • Independent rows — Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods.
  • Ties — Ties in x are broken at random (seeded) for ξ.

The same variables under other dependence measures

MeasureValueSensitive to
Pearson r−0.0277Linear association
Spearman ρ−0.0254Monotonic association
ξ(x → y)0.4019y is a function of x (any shape)
ξ(y → x)0.0034x is a function of y (any shape)
Hoeffding 30·D0.0676Any departure from independence (ranks)
Distance correlation0.4592Any dependence (finite means)
Bias-corrected dCor0.1767Any dependence; ≈ 0 under independence
HSIC (median bandwidth)0.0194Any dependence (kernel)
  • 2 of 120 rows were left out because a value was missing.
  • Chatterjee's ξ(x → y); one-sided test of independence (asymptotic normal p-value).
Python

Chatterjee's ξ(x → y) = 0.402, p < .001, N = 118

Chatterjee's ξ(x → y)
0.4019
z
6.901
p
< .001
n
118

Effect size

  • Chatterjee's ξ(x → y) 0.4019

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

Assumptions

  • Independent rows — Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods.
  • Ties — Ties in x are broken at random (seeded) for ξ.

The same variables under other dependence measures

MeasureValueSensitive to
Pearson r−0.0277Linear association
Spearman ρ−0.0254Monotonic association
ξ(x → y)0.4019y is a function of x (any shape)
ξ(y → x)0.0034x is a function of y (any shape)
Hoeffding 30·D0.0676Any departure from independence (ranks)
Distance correlation0.4592Any dependence (finite means)
Bias-corrected dCor0.1767Any dependence; ≈ 0 under independence
HSIC (median bandwidth)0.0194Any dependence (kernel)
  • 2 of 120 rows were left out because a value was missing.
  • Chatterjee's ξ(x → y); one-sided test of independence (asymptotic normal p-value).

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

  • Xi quadraticf_dependence · x: x · y: y quadratic
  • Xi ties permutationf_dependence · x: x rounded · y: y wave
  • Hoeffding wavef_dependence · x: x · y: y wave
  • Dcor permutation multivariatef_dependence · x: x, x2 · y: y both
  • Dcor t nullf_dependence · x: x · y: y noise
  • Hsic medianf_dependence · x: x · y: y quadratic
  • Hsic unit rawf_dependence · x: x · y: y linear
  • Cross hsicf_dependence · x: x · y: y quadratic

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
  • Monotonic / non-parametric / nominal relationships · Statistics Guide · C — Test association
  • Non-parametric alternatives · Statistics Guide · Additional considerations
  • EDA (correlation, distributions) · DS & ML Decision Guide · Describe — summarize and visualize
  • Correlation analysis (Pearson, Spearman) · DS & ML Decision Guide · Explain — why is it happening?

What you need

X variable(s)numeric · 1–20 columns
ξ and Hoeffding's D take one variable; distance correlation and HSIC accept a set of variables.
Y variable(s)numeric · 1–20 columns
For ξ, the variable whose dependence on x is measured (ξ is directional).

Choices you make

statistics

Dependence measuredefault xi

All measures test the same null (independence) but are sensitive to different kinds of relationship.

  • Chatterjee's ξ (y as a function of x)(default) — 0 under independence, 1 when y is a function of x; detects oscillating and non-monotonic links; directional.
  • Hoeffding's D — Rank statistic measuring how far the joint distribution is from the product of the margins.
  • Distance correlation (dCor) — Zero only under independence (finite means); works for sets of variables. Permutation or bias-corrected t calibration.
  • HSIC (Gaussian kernels) — Kernel measure of dependence between sets of variables; permutation calibration.
  • Cross HSIC (no permutations) — HSIC on one random split into halves, studentized: a normal p-value without permutations; for large n.
  • Cross distance covariance (no permutations) — Distance covariance on one random split into halves, studentized: a normal p-value without permutations.

hypothesis

p-valuedefault auto

How the p-value is obtained; the cross tests are always calibrated by the normal distribution.

  • Automatic(default) — Asymptotic for ξ, permutations for Hoeffding's D, distance correlation and HSIC.
  • Permutation (Monte Carlo) — Shuffle y's rows and recompute; valid at any n under independent rows.
  • Asymptotic — ξ: normal limit with Chatterjee's tie-aware variance. Distance correlation: the bias-corrected dCor t-test.
Permutationsdefault 999

Monte Carlo permutations when the p-value is by permutation; the smallest possible p is 1/(B + 1).

options

Kernel bandwidthdefault median

Kernel width for HSIC: the median distance heuristic, or σ = 1 on standardized data.

  • Median distance (heuristic)(default) — σ = median distance between rows of each variable set, fixed before testing.
  • σ = 1 — A fixed unit bandwidth on the (standardized) scale, as in the guide's example.
Standardize variablesdefault on

Scale each variable to unit SD so measurement units do not decide which variable dominates the distances.

Advanced

Largest sample useddefault 1000

Distance and kernel measures use n × n matrices; above this size a seeded random subsample is analyzed.

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.

  • Independent rows

    Permutation and cross tests assume exchangeable, independent rows; time series or clustered data need block methods.

  • Ties

    Ties in x are broken at random (seeded) for ξ; heavy ties make ξ and Hoeffding's D less powerful.

What it reports

  • Tests: Dependence
measure
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
measure_label
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
statistic
One test of "every component null holds" from several independent tests' p-values.
z
An estimate in standard-error units, compared with the standard normal distribution.
test_statistic
A single number that summarizes how far your data are from what H₀ predicts.
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.
calibration
Each p-value comes from a reference distribution, a simulation of the null, or an exact count: this column says which.
n
How many independent units the analysis used; it sets precision and power.
n_used
How many independent units the analysis used; it sets precision and power.
n_perm
How many independent units the analysis used; it sets precision and power.
count
How many permutations gave a statistic at least as large as the observed one. Empty when the p-value is not from permutations.
xi_xy
How much y is a function of x — 0 under independence, 1 when y is exactly determined by x, any shape.
xi_yx
How much y is a function of x — 0 under independence, 1 when y is exactly determined by x, any shape.
dcor
A correlation built from distances between rows; it is zero only when the variables are independent.
dcor_bc
A correlation built from distances between rows; it is zero only when the variables are independent.
hoeffding_30d
A rank statistic for how far the joint distribution is from what independence would give.
hsic
A kernel measure of dependence between two sets of variables; zero under independence for Gaussian kernels.
pearson
How closely two numbers follow a straight line, from −1 to 1. Outliers can pull it a long way.
spearman
Pearson correlation of the ranks; captures any steadily rising or falling relationship and resists outliers.
bandwidth_x
A kernel measure of dependence between two sets of variables; zero under independence for Gaussian kernels.
bandwidth_y
A kernel measure of dependence between two sets of variables; zero under independence for Gaussian kernels.

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

  • Both engines use the codesplash twins (codesplash.stats.dependence ↔ codesplashr): permutations, the ξ tie-breaking and the cross-test split come from the shared Wichmann–Hill stream, so p-values match exactly.
  • ξ breaks ties in x at random as Chatterjee (2021) prescribes (XICOR does the same); scipy.stats.chatterjeexi keeps the data order instead, so with ties in x its ξ differs. Without ties in x all three agree.
  • Hoeffding's D is reported on the original scale; Hmisc::hoeffd prints 30·D (hoeffding_30d).
Python

The exact script CodeSplash ran for example “Xi quadratic” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Test for any dependence (ξ, Hoeffding, distance correlation, HSIC)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.dependence 1.0.1 · spec 3c303f0c5fe8f8c7
# Dataset: f_dependence (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 dependence
from codesplash.stats.rng import Rng

# %% Data
df = pd.read_parquet("tests/parity/fixtures/f_dependence.parquet", columns=["x", "y quadratic"])
n_input = len(df)
df = df.dropna(subset=["x", "y quadratic"])  # 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 quadratic"])  # infinite values stop the run (registry/errors.yaml)

# %% Dependence
x_cols = ["x"]
y_cols = ["y quadratic"]
measure = "xi"
calibration = "auto"
n_perm = int(999)
bandwidth = "median"
standardize = True
max_n = int(1000)
seed = 42  # shared Wichmann–Hill streams: ties in x, permutations, subsample, split
univariate = len(x_cols) == 1 and len(y_cols) == 1
if measure in ("xi", "hoeffding") and not univariate:
    raise ValueError("ξ and Hoeffding's D compare one x variable with one y variable.")
if set(x_cols) & set(y_cols):
    raise ValueError("A column cannot be both an x and a y variable.")
X = df[x_cols].to_numpy(dtype=float)
Y = df[y_cols].to_numpy(dtype=float)
n = len(df)
if n < 10:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="A dependence test", min=10, n=n)
for col, v in zip(x_cols + y_cols, np.column_stack([X, Y]).T):
    if len(np.unique(v)) < 2:  # a constant variable cannot depend on anything (most measures are 0 / 0)
        cs.cs_error("CS_E_CONSTANT", column=col)
if n > max_n:  # n × n matrices: analyze a seeded random subsample
    idx = np.sort(Rng(seed + 2).permutation(n)[:max_n])
    warnings.append(f"Distance and kernel measures used a random subsample of {max_n} of {n} rows (seed {seed}).")
else:
    idx = np.arange(n)
Xs, Ys = X[idx], Y[idx]
n_used = len(idx) if measure != "xi" else n


def scaled(M):
    return (M - M.mean(axis=0)) / M.std(axis=0, ddof=1) if standardize else M


if calibration == "auto":
    calibration = {"xi": "asymptotic", "hoeffding": "permutation", "dcor": "permutation", "hsic": "permutation"}.get(measure, "normal")
if measure in ("cross_hsic", "cross_dcov"):
    calibration = "normal"
elif calibration == "asymptotic" and measure not in ("xi", "dcor"):
    raise ValueError("Only ξ and distance correlation have an asymptotic test; choose permutations.")
z = test_statistic = dof = count = None
bw_x = bw_y = None
used_perm = calibration == "permutation"
if measure == "xi":
    xv, yv = X[:, 0], Y[:, 0]
    res = dependence.xi(xv, yv, seed)
    statistic = res["statistic"]
    label = "Chatterjee's ξ(x → y)"
    if used_perm:
        pr = dependence.perm_pvalue(lambda pm: dependence.xi(xv, yv[pm], seed)["statistic"], statistic, n, n_perm, seed + 1)
        p, count = pr["p"], pr["count"]
    else:
        z, p = res["z"], res["p"]
elif measure == "hoeffding":
    xv, yv = Xs[:, 0], Ys[:, 0]
    statistic = dependence.hoeffding_d(xv, yv)
    label = "Hoeffding's D"
    pr = dependence.perm_pvalue(lambda pm: dependence.hoeffding_d(xv, yv[pm]), statistic, len(xv), n_perm, seed + 1)
    p, count = pr["p"], pr["count"]
elif measure == "dcor":
    dc = dependence.dcov(scaled(Xs), scaled(Ys))
    if used_perm:
        A, B = dc["A"], dc["B"]
        statistic, test_statistic = dc["dcor"], dc["nv2"]
        label = "Distance correlation"
        m = A.shape[0]
        pr = dependence.perm_pvalue(lambda pm: m * float(np.mean(A * B[np.ix_(pm, pm)])), test_statistic, m, n_perm, seed + 1)
        p, count = pr["p"], pr["count"]
    else:
        statistic, test_statistic, dof, p = dc["dcor_bc"], dc["t"], dc["df"], dc["p_t"]
        label = "Bias-corrected distance correlation"
elif measure == "hsic":
    Xh, Yh = scaled(Xs), scaled(Ys)
    bw_x, bw_y = (dependence.median_bandwidth(Xh), dependence.median_bandwidth(Yh)) if bandwidth == "median" else (1.0, 1.0)
    hs = dependence.hsic(Xh, Yh, bw_x, bw_y)
    statistic = hs["statistic"]
    label = "HSIC"
    Kc, Lc = hs["Kc"], hs["Lc"]
    m = Kc.shape[0]
    pr = dependence.perm_pvalue(lambda pm: float(np.sum(Kc * Lc[np.ix_(pm, pm)]) / (m - 1) ** 2), statistic, m, n_perm, seed + 1)
    p, count = pr["p"], pr["count"]
else:
    Xh, Yh = scaled(Xs), scaled(Ys)
    kernel = "gaussian" if measure == "cross_hsic" else "distance"
    if kernel == "gaussian":
        bw_x, bw_y = (dependence.median_bandwidth(Xh), dependence.median_bandwidth(Yh)) if bandwidth == "median" else (1.0, 1.0)
    res = dependence.cross_stat(Xh, Yh, kernel, bw_x or 1.0, bw_y or 1.0, seed + 3)
    statistic, z, p = res["statistic"], res["z"], res["p"]
    label = "Cross HSIC" if kernel == "gaussian" else "Cross distance covariance"
    n_used = 2 * res["half"]

# %% Profile: the same pair under other measures (estimates only)
xi_xy = xi_yx = hoeffding_30d = pearson = spearman = hsic_med = None
Xp, Yp = scaled(Xs), scaled(Ys)
dcor_all = dependence.dcov(Xp, Yp)
dcor_v, dcor_bc = dcor_all["dcor"], dcor_all["dcor_bc"]
rows = []
if univariate:
    xa, ya = Xs[:, 0], Ys[:, 0]
    pearson = float(np.corrcoef(xa, ya)[0, 1])
    spearman = float(np.corrcoef(stats.rankdata(xa), stats.rankdata(ya))[0, 1])
    xi_xy = dependence.xi(xa, ya, seed)["statistic"]
    xi_yx = dependence.xi(ya, xa, seed)["statistic"]
    hoeffding_30d = 30 * dependence.hoeffding_d(xa, ya)
    rows += [{"measure": "Pearson r", "value": pearson, "detects": "Linear association"},
             {"measure": "Spearman ρ", "value": spearman, "detects": "Monotonic association"},
             {"measure": "ξ(x → y)", "value": xi_xy, "detects": "y is a function of x (any shape)"},
             {"measure": "ξ(y → x)", "value": xi_yx, "detects": "x is a function of y (any shape)"},
             {"measure": "Hoeffding 30·D", "value": hoeffding_30d, "detects": "Any departure from independence (ranks)"}]
hsic_med = dependence.hsic(Xp, Yp, dependence.median_bandwidth(Xp), dependence.median_bandwidth(Yp))["statistic"]
rows += [{"measure": "Distance correlation", "value": dcor_v, "detects": "Any dependence (finite means)"},
         {"measure": "Bias-corrected dCor", "value": dcor_bc, "detects": "Any dependence; ≈ 0 under independence"},
         {"measure": "HSIC (median bandwidth)", "value": hsic_med, "detects": "Any dependence (kernel)"}]

# %% Result
alpha = 0.050000000000000044
names = lambda cols: ", ".join(cols)
verdict = (f"The variables are not independent ({cs.fmt_p(p)})." if p < alpha
           else f"The data are compatible with independence ({cs.fmt_p(p)}).")
summary = f"{label} between {names(x_cols)} and {names(y_cols)} was {statistic:.3f} (n = {n_used}). {verdict}"
how = {"asymptotic": "asymptotic normal p-value" if measure == "xi" else "bias-corrected t-test",
       "permutation": f"{n_perm} Monte Carlo permutations (seed {seed})", "normal": "studentized cross statistic, standard normal p-value"}[calibration]
apa = f"{label} = {statistic:.3f}, {cs.fmt_p(p)}, N = {n_used}"
statistics_rows = [{"key": "statistic", "label": label, "value": statistic}]
if test_statistic is not None:
    statistics_rows.append({"key": "test_statistic", "label": "t" if dof is not None else "nV²", "value": test_statistic})
if z is not None:
    statistics_rows.append({"key": "z", "label": "z", "value": z})
statistics_rows += [{"key": "p", "label": "p", "value": p, "format": "p"}, {"key": "n", "label": "n", "value": n_used}]
charts = []
if univariate:
    sel = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int))
    charts.append(cs.chart("scatter", "scatter", f"{y_cols[0]} against {x_cols[0]}", {"x": cs.col(x_cols[0], X[sel, 0]), "y": cs.col(y_cols[0], Y[sel, 0])}))
cs.publish({
    "method": "correlation.dependence",
    "methodVersion": "1.0.1",
    "title": f"Test of independence: {label}",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n_used,
    "summary": summary,
    "apa": apa,
    "statistics": statistics_rows,
    "tables": [{"key": "profile", "title": "The same variables under other dependence measures", "columns": [
        {"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
        {"key": "detects", "label": "Sensitive to", "type": "string"}], "rows": rows}],
    "effectSizes": [{"key": "statistic", "label": label, "value": statistic, "method": how}],
    "assumptions": [
        {"key": "independence", "label": "Independent rows", "status": "info",
         "detail": "Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods."},
        {"key": "ties", "label": "Ties", "status": "info",
         "detail": "Ties in x are broken at random (seeded) for ξ." if measure == "xi" else "Ties are handled by midranks or exact distances."},
    ],
    "charts": charts,
    "warnings": warnings,
    "notes": [f"{label}; one-sided test of independence ({how})."],
    "values": {"measure": measure, "measure_label": label, "statistic": statistic, "z": z, "test_statistic": test_statistic, "df": dof,
               "p": p, "calibration": calibration, "n": n, "n_used": n_used, "n_perm": n_perm if used_perm else None, "count": count,
               "xi_xy": xi_xy, "xi_yx": xi_yx, "dcor": dcor_v, "dcor_bc": dcor_bc, "hoeffding_30d": hoeffding_30d, "hsic": hsic_med,
               "pearson": pearson, "spearman": spearman, "bandwidth_x": bw_x, "bandwidth_y": bw_y},
})
R

The exact script CodeSplash ran for example “Xi quadratic” · R version 4.5.1 (2025-06-13)

# Test for any dependence (ξ, Hoeffding, distance correlation, HSIC)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.dependence 1.0.1 · spec 3c303f0c5fe8f8c7
# Dataset: f_dependence (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/f_dependence.parquet", col_select = c("x", "y quadratic")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x", "y quadratic")]), , 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 quadratic"))  # infinite values stop the run (registry/errors.yaml)

# %% Dependence
x_cols <- c("x")
y_cols <- c("y quadratic")
measure <- "xi"
calibration <- "auto"
n_perm <- as.integer(999)
bandwidth <- "median"
standardize <- TRUE
max_n <- as.integer(1000)
seed <- 42  # shared Wichmann-Hill streams: ties in x, permutations, subsample, split
univariate <- length(x_cols) == 1 && length(y_cols) == 1
if (measure %in% c("xi", "hoeffding") && !univariate) stop("ξ and Hoeffding's D compare one x variable with one y variable.")
if (length(intersect(x_cols, y_cols))) stop("A column cannot be both an x and a y variable.")
X <- as.matrix(df[x_cols]); storage.mode(X) <- "double"
Y <- as.matrix(df[y_cols]); storage.mode(Y) <- "double"
n <- nrow(df)
if (n < 10) cs_error("CS_E_TOO_FEW_ROWS", what = "A dependence test", min = 10, n = n)
for (col in c(x_cols, y_cols)) {
  # a constant variable cannot depend on anything (most measures are 0 / 0)
  if (length(unique(as.double(df[[col]]))) < 2) cs_error("CS_E_CONSTANT", column = col)
}
if (n > max_n) {  # n x n matrices: analyze a seeded random subsample
  idx <- sort(cs_rperm(cs_rng(seed + 2), n)[seq_len(max_n)])
  warnings <- c(warnings, sprintf("Distance and kernel measures used a random subsample of %d of %d rows (seed %d).", max_n, n, as.integer(seed)))
} else {
  idx <- seq_len(n)
}
Xs <- X[idx, , drop = FALSE]
Ys <- Y[idx, , drop = FALSE]
n_used <- if (measure != "xi") length(idx) else n
scaled <- function(M) {
  if (!standardize) return(M)
  sweep(sweep(M, 2, colMeans(M), "-"), 2, apply(M, 2, stats::sd), "/")
}

if (calibration == "auto") {
  calibration <- c(xi = "asymptotic", hoeffding = "permutation", dcor = "permutation", hsic = "permutation")[measure]
  if (is.na(calibration)) calibration <- "normal"
  calibration <- unname(calibration)
}
if (measure %in% c("cross_hsic", "cross_dcov")) {
  calibration <- "normal"
} else if (calibration == "asymptotic" && !(measure %in% c("xi", "dcor"))) {
  stop("Only ξ and distance correlation have an asymptotic test; choose permutations.")
}
z <- NULL; test_statistic <- NULL; dof <- NULL; count <- NULL
bw_x <- NULL; bw_y <- NULL
used_perm <- calibration == "permutation"
if (measure == "xi") {
  xv <- X[, 1]; yv <- Y[, 1]
  res <- cs_xi(xv, yv, seed)
  statistic <- res$statistic
  label <- "Chatterjee's ξ(x → y)"
  if (used_perm) {
    pr <- cs_perm_pvalue(function(pm) cs_xi(xv, yv[pm], seed)$statistic, statistic, n, n_perm, seed + 1)
    p <- pr$p; count <- pr$count
  } else {
    z <- res$z; p <- res$p
  }
} else if (measure == "hoeffding") {
  xv <- Xs[, 1]; yv <- Ys[, 1]
  statistic <- cs_hoeffding_d(xv, yv)
  label <- "Hoeffding's D"
  pr <- cs_perm_pvalue(function(pm) cs_hoeffding_d(xv, yv[pm]), statistic, length(xv), n_perm, seed + 1)
  p <- pr$p; count <- pr$count
} else if (measure == "dcor") {
  dc <- cs_dcov(scaled(Xs), scaled(Ys))
  if (used_perm) {
    A <- dc$A; B <- dc$B
    statistic <- dc$dcor; test_statistic <- dc$nv2
    label <- "Distance correlation"
    m <- nrow(A)
    pr <- cs_perm_pvalue(function(pm) m * mean(A * B[pm, pm]), test_statistic, m, n_perm, seed + 1)
    p <- pr$p; count <- pr$count
  } else {
    statistic <- dc$dcor_bc; test_statistic <- dc$t; dof <- dc$df; p <- dc$p_t
    label <- "Bias-corrected distance correlation"
  }
} else if (measure == "hsic") {
  Xh <- scaled(Xs); Yh <- scaled(Ys)
  if (bandwidth == "median") { bw_x <- cs_median_bandwidth(Xh); bw_y <- cs_median_bandwidth(Yh) } else { bw_x <- 1; bw_y <- 1 }
  hs <- cs_hsic(Xh, Yh, bw_x, bw_y)
  statistic <- hs$statistic
  label <- "HSIC"
  Kc <- hs$Kc; Lc <- hs$Lc
  m <- nrow(Kc)
  pr <- cs_perm_pvalue(function(pm) sum(Kc * Lc[pm, pm]) / (m - 1)^2, statistic, m, n_perm, seed + 1)
  p <- pr$p; count <- pr$count
} else {
  Xh <- scaled(Xs); Yh <- scaled(Ys)
  kernel <- if (measure == "cross_hsic") "gaussian" else "distance"
  if (kernel == "gaussian") {
    if (bandwidth == "median") { bw_x <- cs_median_bandwidth(Xh); bw_y <- cs_median_bandwidth(Yh) } else { bw_x <- 1; bw_y <- 1 }
  }
  res <- cs_cross_stat(Xh, Yh, kernel, if (is.null(bw_x)) 1 else bw_x, if (is.null(bw_y)) 1 else bw_y, seed + 3)
  statistic <- res$statistic; z <- res$z; p <- res$p
  label <- if (kernel == "gaussian") "Cross HSIC" else "Cross distance covariance"
  n_used <- 2 * res$half
}

# %% Profile: the same pair under other measures (estimates only)
xi_xy <- NULL; xi_yx <- NULL; hoeffding_30d <- NULL; pearson <- NULL; spearman <- NULL
Xp <- scaled(Xs); Yp <- scaled(Ys)
dcor_all <- cs_dcov(Xp, Yp)
dcor_v <- dcor_all$dcor; dcor_bc <- dcor_all$dcor_bc
rows <- list()
if (univariate) {
  xa <- Xs[, 1]; ya <- Ys[, 1]
  pearson <- stats::cor(xa, ya)
  spearman <- stats::cor(rank(xa), rank(ya))
  xi_xy <- cs_xi(xa, ya, seed)$statistic
  xi_yx <- cs_xi(ya, xa, seed)$statistic
  hoeffding_30d <- 30 * cs_hoeffding_d(xa, ya)
  rows <- list(list(measure = "Pearson r", value = pearson, detects = "Linear association"),
               list(measure = "Spearman ρ", value = spearman, detects = "Monotonic association"),
               list(measure = "ξ(x → y)", value = xi_xy, detects = "y is a function of x (any shape)"),
               list(measure = "ξ(y → x)", value = xi_yx, detects = "x is a function of y (any shape)"),
               list(measure = "Hoeffding 30·D", value = hoeffding_30d, detects = "Any departure from independence (ranks)"))
}
hsic_med <- cs_hsic(Xp, Yp, cs_median_bandwidth(Xp), cs_median_bandwidth(Yp))$statistic
rows <- c(rows, list(list(measure = "Distance correlation", value = dcor_v, detects = "Any dependence (finite means)"),
                     list(measure = "Bias-corrected dCor", value = dcor_bc, detects = "Any dependence; ≈ 0 under independence"),
                     list(measure = "HSIC (median bandwidth)", value = hsic_med, detects = "Any dependence (kernel)")))

# %% Result
alpha <- 0.050000000000000044
verdict <- if (p < alpha) sprintf("The variables are not independent (%s).", cs_fmt_p(p)) else sprintf("The data are compatible with independence (%s).", cs_fmt_p(p))
summary <- sprintf("%s between %s and %s was %.3f (n = %d). %s", label, paste(x_cols, collapse = ", "), paste(y_cols, collapse = ", "), statistic, as.integer(n_used), verdict)
how <- switch(calibration,
              asymptotic = if (measure == "xi") "asymptotic normal p-value" else "bias-corrected t-test",
              permutation = sprintf("%d Monte Carlo permutations (seed %d)", n_perm, as.integer(seed)),
              normal = "studentized cross statistic, standard normal p-value")
apa <- sprintf("%s = %.3f, %s, N = %d", label, statistic, cs_fmt_p(p), as.integer(n_used))
statistics_rows <- list(list(key = "statistic", label = label, value = statistic))
if (!is.null(test_statistic)) statistics_rows <- c(statistics_rows, list(list(key = "test_statistic", label = if (!is.null(dof)) "t" else "nV²", value = test_statistic)))
if (!is.null(z)) statistics_rows <- c(statistics_rows, list(list(key = "z", label = "z", value = z)))
statistics_rows <- c(statistics_rows, list(list(key = "p", label = "p", value = p, format = "p"), list(key = "n", label = "n", value = n_used)))
charts <- list()
if (univariate) {
  sel <- unique(round(seq(1, n, length.out = min(n, 5000))))
  charts <- list(cs_chart("scatter", "scatter", sprintf("%s against %s", y_cols[1], x_cols[1]), list(x = cs_col(x_cols[1], X[sel, 1]), y = cs_col(y_cols[1], Y[sel, 1]))))
}
cs_publish(list(
  method = "correlation.dependence",
  methodVersion = "1.0.1",
  title = sprintf("Test of independence: %s", label),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n_used,
  summary = summary,
  apa = apa,
  statistics = statistics_rows,
  tables = list(list(key = "profile", title = "The same variables under other dependence measures", columns = list(
    list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", type = "number"),
    list(key = "detects", label = "Sensitive to", type = "string")), rows = rows)),
  effectSizes = list(list(key = "statistic", label = label, value = statistic, method = how)),
  assumptions = list(
    list(key = "independence", label = "Independent rows", status = "info",
         detail = "Permutation and cross tests assume exchangeable rows; for time series or clustered data use block methods."),
    list(key = "ties", label = "Ties", status = "info",
         detail = if (measure == "xi") "Ties in x are broken at random (seeded) for ξ." else "Ties are handled by midranks or exact distances.")
  ),
  charts = charts,
  warnings = warnings,
  notes = list(sprintf("%s; one-sided test of independence (%s).", label, how)),
  values = list(measure = measure, measure_label = label, statistic = statistic, z = z, test_statistic = test_statistic, df = dof,
                p = p, calibration = calibration, n = n, n_used = n_used, n_perm = if (used_perm) n_perm else NULL, count = count,
                xi_xy = xi_xy, xi_yx = xi_yx, dcor = dcor_v, dcor_bc = dcor_bc, hoeffding_30d = hoeffding_30d, hsic = hsic_med,
                pearson = pearson, spearman = spearman, bandwidth_x = bw_x, bandwidth_y = bw_y)
))

Sources

  • Chatterjee, S. (2021). A new coefficient of correlation. Journal of the American Statistical Association, 116, 2009–2022.
  • Hoeffding, W. (1948). A non-parametric test of independence. Annals of Mathematical Statistics, 19, 546–557.
  • Székely, G. J., Rizzo, M. L., & Bakirov, N. K. (2007). Measuring and testing dependence by correlation of distances. Annals of Statistics, 35, 2769–2794.
  • Székely, G. J., & Rizzo, M. L. (2013). The distance correlation t-test of independence in high dimension. Journal of Multivariate Analysis, 117, 193–213.
  • Gretton, A., Fukumizu, K., Teo, C. H., Song, L., Schölkopf, B., & Smola, A. J. (2008). A kernel statistical test of independence. NeurIPS 20.
  • Shekhar, S., Kim, I., & Ramdas, A. (2023). A permutation-free kernel independence test. Journal of Machine Learning Research, 24(369), 1–68.
  • Phipson, B., & Smyth, G. K. (2010). Permutation p-values should never be zero. Statistical Applications in Genetics and Molecular Biology, 9(1).

From the CodeSplash method registry · correlation.dependence v1.0.1.