CAssociation · correlation.test
Correlation test (Pearson / Spearman / Kendall)
Do two numeric variables move together, and how strongly?
Pearson's r (linear), Spearman's ρ or Kendall's τ_b (monotonic) with a significance test and a Fisher-z confidence interval.
A real result
Example “Pearson”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
r(30) = −.87, p < .001, 95% CI [−.93, −.74]
- r
- −0.8677
- p
- < .001
- 95% CI
- [−0.9338, −0.7441]
- n
- 32
Effect size
- r −0.8677 95% CI [−0.9338, −0.7441] · large
Plots
View data
| weight (1000 lbs) | mpg |
|---|---|
| 2.620 | 21 |
| 2.875 | 21 |
| 2.320 | 22.800 |
| 3.215 | 21.400 |
| 3.440 | 18.700 |
| 3.460 | 18.100 |
| 3.570 | 14.300 |
| 3.190 | 24.400 |
| 3.150 | 22.800 |
| 3.440 | 19.200 |
| 3.440 | 17.800 |
| 4.070 | 16.400 |
| 3.730 | 17.300 |
| 3.780 | 15.200 |
| 5.250 | 10.400 |
| 5.424 | 10.400 |
| 5.345 | 14.700 |
| 2.200 | 32.400 |
| 1.615 | 30.400 |
| 1.835 | 33.900 |
| 2.465 | 21.500 |
| 3.520 | 15.500 |
| 3.435 | 15.200 |
| 3.840 | 13.300 |
| 3.845 | 19.200 |
| 1.935 | 27.300 |
| 2.140 | 26 |
| 1.513 | 30.400 |
| 3.170 | 15.800 |
| 2.770 | 19.700 |
| 3.570 | 15 |
| 2.780 | 21.400 |
Assumptions
- Linear relationship — Check a scatter plot: correlation coefficients summarize only this kind of association.
- Outlying points — No point is more than 3.29 SD from either mean.
- Pearson correlation; alternative: two-sided; asymptotic p-value.
r(30) = −.87, p < .001, 95% CI [−.93, −.74]
- r
- −0.8677
- p
- < .001
- 95% CI
- [−0.9338, −0.7441]
- n
- 32
Effect size
- r −0.8677 95% CI [−0.9338, −0.7441] · large
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Linear relationship — Check a scatter plot: correlation coefficients summarize only this kind of association.
- Outlying points — No point is more than 3.29 SD from either mean.
- Pearson correlation; alternative: two-sided; asymptotic 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
- Pearsonmtcars · x: weight (1000 lbs) · y: mpg
- Spearman greateriris · x: Sepal.Length · y: Petal.Length
- Kendall ties missingairquality · x: Ozone · y: Temp
- Pearson lessairquality · x: Wind · y: Ozone
- Degenerate constantdegenerate/constant · x: x · y: y
- Degenerate n2 kendalldegenerate/n2 · x: x · y: y
- Degenerate infdegenerate/inf · x: x · y: y
- Degenerate emptydegenerate/empty_after_filter · 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
- Ordinal variables: Spearman / Kendall, polychoric · 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
- First variablenumeric · 1 column
- The first numeric variable.
- Second variablenumeric · 1 column
- The second numeric variable.
Choices you make
statistics
- Coefficientdefault pearson
Pearson measures straight-line association; Spearman and Kendall use ranks, so they tolerate outliers and curves.
- Pearson r (linear)(default) — Measures straight-line association on raw values; pick it for roughly linear relationships without outliers.
- Spearman ρ (ranks) — Correlates ranks; pick it for monotonic curves or outliers.
- Kendall τ_b (ranks, ties) — Counts concordant pairs, adjusted for ties; pick it for small samples or many ties.
hypothesis
- Alternative hypothesisdefault two-sided
Which direction counts as evidence. Keep two-sided unless you fixed the direction before seeing the data.
- Correlation ≠ 0(default) — Tests for any correlation in either direction; keep it unless you fixed a direction before seeing the data.
- Positive (> 0) — Tests only for a positive correlation; pick it only if you fixed this direction before seeing the data.
- Negative (< 0) — Tests only for a negative correlation; pick it only if you fixed this direction before seeing the data.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
- Null correlation ρ0default 0
Correlation under the null hypothesis. Leave 0 to test for any correlation; a nonzero value tests r against it on the Fisher z scale.
- Lensdefault none
Also test against bounds you set before seeing the data: equivalence, a minimal effect or non-inferiority.
- Off(default) — Test for a difference only.
- Equivalence (TOST) — Show the effect lies inside your bounds (two one-sided tests).
- Minimal effect — Show the effect lies outside your bounds, i.e. is big enough to matter.
- Lower bound (correlation (r, ρ or τ))default —
The smallest effect that matters on the low side (for non-inferiority: the margin, as a negative number).
- Upper bound (correlation (r, ρ or τ))default —
The smallest effect that matters on the high side.
options
- p-valuedefault asymptotic
How the p-value is computed. The large-sample p suits most data; exact and permutation p-values hold at small n.
- Large-sample (t or normal)(default) — Uses the t distribution for Pearson and Spearman and the normal approximation for Kendall; fine for moderate samples.
- Exact (Kendall, no ties) — Uses the exact null distribution of Kendall's statistic; for small samples without tied values.
- Permutation — Shuffles one variable many times and counts how often the shuffled coefficient is as extreme; valid at any size, ties included.
- Permutationsdefault 9999
Number of shuffles. More shuffles make the permutation p-value more precise and the run slower.
- Random seeddefault 1
Fixes the shuffles so reruns give identical results, in Python and in R.
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 (Pearson) or monotonic (rank) relationship
Independent observationsNot checked from data: state why it holds
Outlying points
Points more than 3.29 SD from either mean; they can dominate Pearson's r.
- If violated → Spearman rank correlation — Ranks limit the pull of outlying points and capture any monotonic (not only linear) association. Changes the question: Measures monotonic association between ranks instead of linear association between values.
What it reports
- Tests: Correlation
- estimate
- How much the outcome changes for a one-unit change in a predictor, holding the others fixed.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- n
- How many independent units the analysis used; it sets precision and power.
- 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.
- method
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- n_outliers
- How many independent units the analysis used; it sets precision and power.
Per group, level or term: rho0, z_rho0, p_method, n_perm, perm_count, lens_p (when a lens is on), lens_ci_low (when a lens is on), lens_ci_high (when a lens is on), lens_verdict (when a lens is on)
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Spearman and Kendall p-values are asymptotic in both engines (R's exact = FALSE is pinned; R would otherwise use exact Spearman p for n < 1290).
- Spearman/Kendall intervals are two-sided Fisher z intervals (Bonett–Wright / Fieller SEs) computed explicitly in both engines.
- Optional p-values (codesplash.stats.stat_options ≡ cs_*): the exact Kendall p uses the Mahonian distribution of discordant pairs (equals cor.test(exact = TRUE) and scipy's method = 'exact'); permutation p-values shuffle y with the shared Wichmann–Hill stream, so both engines use the same permutations; the nonzero-null test is Fisher's z with SE 1/√(n − 3).
The exact script CodeSplash ran for example “Pearson” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Correlation test (Pearson / Spearman / Kendall)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.test 1.2.0 · spec fcbdfe5c562178c2
# Dataset: mtcars (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
# %% Data
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=["weight (1000 lbs)", "mpg"])
n_input = len(df)
df = df.dropna(subset=["weight (1000 lbs)", "mpg"]) # 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, ["weight (1000 lbs)", "mpg"]) # infinite values stop the run (registry/errors.yaml)
# %% Helpers
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
"""Benchmark label for an effect size (rule set named in the result)."""
if x is None or not np.isfinite(x):
return "undetermined"
for cut, label in zip(cuts, labels):
if abs(x) < cut:
return label
return labels[-1]
# %% Test
a, b = "weight (1000 lbs)", "mpg"
x = df[a].to_numpy(dtype=float)
y = df[b].to_numpy(dtype=float)
n = len(x)
if n == 0:
cs.cs_error("CS_E_NO_ROWS")
for col, v in ((a, x), (b, y)):
if np.isinf(v).any():
cs.cs_error("CS_E_NOT_FINITE", column=col, count=int(np.isinf(v).sum()))
if n < 3:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A correlation test", min=3, n=n)
for col, v in ((a, x), (b, y)):
if len(np.unique(v)) < 2:
cs.cs_error("CS_E_CONSTANT", column=col)
method = "pearson"
alternative = "two-sided"
conf = 0.95
z_crit = stats.norm.ppf(1 - (1 - conf) / 2)
t = dof = None
# Owner decision: intervals are left empty when they are undefined, as R's cor.test does at n < 4 (the
# Fieller SE for Kendall's tau-b also needs n > 4).
ci_defined = n >= 4 and (method != "kendall" or n > 4)
ci_low = ci_high = None
def t_of(r, dof): # t = r √(df / (1 − r²)); ±inf when |r| = 1, as in R
return float(r * np.sqrt(dof / (1 - r**2))) if abs(r) < 1 else float(np.copysign(np.inf, r))
if method == "pearson":
res = stats.pearsonr(x, y, alternative=alternative)
estimate, p = float(res.statistic), float(res.pvalue)
if ci_defined:
ci = res.confidence_interval(confidence_level=conf) # Fisher z (one-sided when the test is)
ci_low, ci_high = float(ci.low), float(ci.high)
dof = n - 2
t = t_of(estimate, dof)
symbol, ci_note = "r", "Fisher z interval"
elif method == "spearman":
res = stats.spearmanr(x, y, alternative=alternative) # pinned: t approximation (R: exact = FALSE)
estimate, p = float(res.statistic), float(res.pvalue)
dof = n - 2
t = t_of(estimate, dof)
if ci_defined:
se = np.sqrt((1 + estimate**2 / 2) / (n - 3)) # Bonett & Wright (2000)
ci_low, ci_high = (float(np.tanh(np.arctanh(estimate) + s * z_crit * se)) for s in (-1, 1))
symbol, ci_note = "ρ", "two-sided Fisher z interval with the Bonett–Wright SE"
else:
res = stats.kendalltau(x, y, variant="b", method="asymptotic", alternative=alternative) # tau-b, tie-corrected z
estimate, p = float(res.statistic), float(res.pvalue)
if ci_defined:
se = np.sqrt(0.437 / (n - 4)) # Fieller, Hartley & Pearson (1957)
ci_low, ci_high = (float(np.tanh(np.arctanh(estimate) + s * z_crit * se)) for s in (-1, 1))
symbol, ci_note = "τ_b", "two-sided Fisher z interval with the Fieller SE"
# %% Optional calibrations (Stage 12.7; the defaults leave everything above unchanged)
from codesplash.stats import stat_options as csopt
rho0 = 0
p_method = "asymptotic"
extra = {}
p_note = "asymptotic p-value"
if rho0 != 0:
if method != "pearson":
cs.cs_error("CS_E_INVALID_OPTION", option="A nonzero null correlation", allowed="used with Pearson's r", value=method)
if p_method != "asymptotic":
cs.cs_error("CS_E_INVALID_OPTION", option="The p-value method", allowed="large-sample with a nonzero null correlation", value=p_method)
if n < 4:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A test against a nonzero null correlation", min=4, n=n)
z_rho0, p = csopt.rho0_test(estimate, n, rho0, alternative)
extra.update({"rho0": rho0, "z_rho0": z_rho0})
p_note = f"Fisher z test against ρ0 = {rho0:g}"
if p_method == "exact":
if method != "kendall":
cs.cs_error("CS_E_INVALID_OPTION", option="An exact p-value", allowed="used with Kendall's tau (use the permutation p-value)", value=method)
if len(np.unique(x)) < n or len(np.unique(y)) < n:
cs.cs_error("CS_E_INVALID_OPTION", option="An exact Kendall p-value", allowed="used without tied values (use the permutation p-value)", value="tied values")
if n > 500:
cs.cs_error("CS_E_INVALID_OPTION", option="An exact Kendall p-value", allowed="used with at most 500 rows", value=f"{n} rows")
p = csopt.kendall_exact_p(x, y, alternative)["p"]
p_note = "exact p-value (no ties)"
elif p_method == "permutation":
n_perm, seed = int(9999), int(1)
perm = csopt.corr_perm_p(x, y, method, alternative, n_perm, seed)
p = perm["p"]
extra.update({"n_perm": perm["b"], "perm_count": perm["count"]})
p_note = f"permutation p-value ({perm['b']} permutations, (count + 1) / (B + 1))"
if p_method != "asymptotic":
extra["p_method"] = p_method
# %% Lens: on the Fisher z scale with the coefficient's own SE, bounds atanh'd, interval back-transformed
lens_kind = "none"
lens = None
if lens_kind != "none" and not ci_defined:
warnings.append(cs.cs_warning("CS_W_SMALL_SAMPLE", n=n, consequence="the lens test needs a confidence interval and is not reported."))
elif lens_kind != "none":
from codesplash.stats import means as csm
lens_low, lens_high = None, None
for bound in (lens_low, lens_high):
if bound is not None and not -1 < bound < 1:
raise ValueError("Lens bounds for a correlation must lie strictly between −1 and 1.")
if method == "pearson":
se_z = 1 / np.sqrt(n - 3)
elif method == "spearman":
se_z = np.sqrt((1 + estimate**2 / 2) / (n - 3))
else:
se_z = np.sqrt(0.437 / (n - 4))
lens = csm.lens(lens_kind, float(np.arctanh(estimate)), float(se_z), None,
None if lens_low is None else float(np.arctanh(lens_low)), None if lens_high is None else float(np.arctanh(lens_high)), 1 - conf)
lens["lens_ci_low"], lens["lens_ci_high"] = float(np.tanh(lens["lens_ci_low"])), float(np.tanh(lens["lens_ci_high"]))
# %% Assumptions
zx = (x - x.mean()) / x.std(ddof=1)
zy = (y - y.mean()) / y.std(ddof=1)
n_outliers = int(np.sum((np.abs(zx) > 3.29) | (np.abs(zy) > 3.29)))
if method == "pearson":
out_status = "warn" if n_outliers else "pass"
out_detail = (f"{n_outliers} point(s) more than 3.29 SD from a mean can dominate Pearson's r; compare with Spearman's ρ."
if n_outliers else "No point is more than 3.29 SD from either mean.")
else:
out_status = "info"
out_detail = f"{n_outliers} point(s) more than 3.29 SD from a mean; rank correlations are robust to them."
# %% Result
alpha = 1 - conf
size = magnitude(estimate, (0.1, 0.3, 0.5))
direction = "positive" if estimate > 0 else "negative"
significance = (
f"The association is statistically significant ({cs.fmt_p(p)})." if p < alpha
else f"The data are compatible with no association ({cs.fmt_p(p)})."
)
label = {"pearson": "Pearson correlation", "spearman": "Spearman rank correlation", "kendall": "Kendall's tau-b"}[method]
ci_text = f", {conf:.0%} CI [{ci_low:.2f}, {ci_high:.2f}]" if ci_low is not None else ""
summary = (
f"{a} and {b} show a {size} {direction} {'linear' if method == 'pearson' else 'monotonic'} association "
f"({symbol} = {estimate:.2f}{ci_text}, n = {n}). {significance}"
)
if lens:
summary += f" Lens ({lens_kind.replace('_', ' ')}): {lens['lens_verdict']} ({cs.fmt_p(lens['lens_p'])})."
ci_apa = (f", {conf:.0%} CI [{cs.fmt_num(ci_low, leading_zero=False)}, {cs.fmt_num(ci_high, leading_zero=False)}]"
if ci_low is not None else "")
apa = (
f"{symbol}({dof}) = {cs.fmt_num(estimate, leading_zero=False)}, {cs.fmt_p(p)}{ci_apa}"
if dof is not None
else f"{symbol} = {cs.fmt_num(estimate, leading_zero=False)}, {cs.fmt_p(p)}, N = {n}"
)
chart_rows = np.unique(np.round(np.linspace(0, n - 1, min(n, 5000))).astype(int))
cs.publish({
"method": "correlation.test",
"methodVersion": "1.2.0",
"title": label,
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": apa,
"statistics": [
{"key": "estimate", "label": symbol, "value": estimate},
{"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "ci", "label": f"{conf:.0%} CI", "value": [ci_low, ci_high] if ci_low is not None else None},
{"key": "n", "label": "n", "value": n},
] + ([{"key": "lens_p", "label": f"Lens p ({lens_kind.replace('_', ' ')})", "value": lens["lens_p"], "format": "p"}] if lens else []),
"tables": [],
"effectSizes": [{"key": "estimate", "label": symbol, "value": estimate, "ciLow": ci_low, "ciHigh": ci_high, "ciLevel": conf,
"method": ci_note, "magnitude": size, "ruleSet": "Cohen (1988), r"}],
"assumptions": [{"key": "form", "label": "Linear relationship" if method == "pearson" else "Monotonic relationship", "status": "info",
"detail": "Check a scatter plot: correlation coefficients summarize only this kind of association."},
{"key": "outliers", "label": "Outlying points", "status": out_status, "statistic": n_outliers, "detail": out_detail}],
"charts": [cs.chart("scatter", "scatter", f"{b} against {a}", {"x": cs.col(a, x[chart_rows]), "y": cs.col(b, y[chart_rows])})],
"warnings": warnings,
"notes": [f"{label}; alternative: {alternative}; {p_note}."]
+ ([f"The lens interval [{lens['lens_ci_low']:.3g}, {lens['lens_ci_high']:.3g}] is the {1 - 2 * (1 - conf):.0%} Fisher z interval for {symbol}."] if lens else []),
"values": {"estimate": estimate, "p": p, "ci_low": ci_low, "ci_high": ci_high, "n": n, "t": t,
"df": None if dof is None else float(dof), "method": method, "n_outliers": n_outliers, **(lens or {}), **extra},
})
The exact script CodeSplash ran for example “Pearson” · R version 4.5.1 (2025-06-13)
# Correlation test (Pearson / Spearman / Kendall)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.test 1.2.0 · spec fcbdfe5c562178c2
# Dataset: mtcars (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/mtcars.parquet", col_select = c("weight (1000 lbs)", "mpg")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("weight (1000 lbs)", "mpg")]), , 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("weight (1000 lbs)", "mpg")) # infinite values stop the run (registry/errors.yaml)
# %% Helpers
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
# Benchmark label for an effect size (rule set named in the result)
if (is.null(x) || !is.finite(x)) return("undetermined")
labels[findInterval(abs(x), cuts) + 1]
}
# %% Test
a <- "weight (1000 lbs)"
b <- "mpg"
x <- df[[a]]
y <- df[[b]]
n <- length(x)
if (n == 0) cs_error("CS_E_NO_ROWS")
for (col in c(a, b)) {
if (any(is.infinite(df[[col]]))) cs_error("CS_E_NOT_FINITE", column = col, count = sum(is.infinite(df[[col]])))
}
if (n < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "A correlation test", min = 3, n = n)
for (col in c(a, b)) {
if (length(unique(df[[col]])) < 2) cs_error("CS_E_CONSTANT", column = col)
}
method <- "pearson"
alternative <- "two-sided"
conf <- 0.95
z_crit <- qnorm(1 - (1 - conf) / 2)
# pinned: exact = FALSE (asymptotic p for Spearman and Kendall, as in scipy); no continuity correction
res <- cor.test(x, y, method = method, alternative = sub("-", ".", alternative, fixed = TRUE), conf.level = conf, exact = FALSE)
estimate <- unname(res$estimate)
p <- res$p.value
t <- NULL
dof <- NULL
# Owner decision: intervals are left empty when they are undefined, as cor.test does at n < 4 (the
# Fieller SE for Kendall's tau-b also needs n > 4).
ci_defined <- n >= 4 && (method != "kendall" || n > 4)
ci_low <- NULL
ci_high <- NULL
if (method == "pearson") {
if (ci_defined) {
ci_low <- res$conf.int[1] # Fisher z (one-sided when the test is)
ci_high <- res$conf.int[2]
}
dof <- n - 2
t <- unname(res$statistic)
symbol <- "r"
ci_note <- "Fisher z interval"
} else if (method == "spearman") {
dof <- n - 2
t <- estimate * sqrt(dof / (1 - estimate^2))
if (ci_defined) {
se <- sqrt((1 + estimate^2 / 2) / (n - 3)) # Bonett & Wright (2000)
ci_low <- tanh(atanh(estimate) - z_crit * se)
ci_high <- tanh(atanh(estimate) + z_crit * se)
}
symbol <- "ρ"
ci_note <- "two-sided Fisher z interval with the Bonett–Wright SE"
} else {
if (ci_defined) {
se <- sqrt(0.437 / (n - 4)) # Fieller, Hartley & Pearson (1957)
ci_low <- tanh(atanh(estimate) - z_crit * se)
ci_high <- tanh(atanh(estimate) + z_crit * se)
}
symbol <- "τ_b"
ci_note <- "two-sided Fisher z interval with the Fieller SE"
}
# %% Optional calibrations (Stage 12.7; the defaults leave everything above unchanged)
rho0 <- 0
p_method <- "asymptotic"
extra <- list()
p_note <- "asymptotic p-value"
if (rho0 != 0) {
if (method != "pearson") cs_error("CS_E_INVALID_OPTION", option = "A nonzero null correlation", allowed = "used with Pearson's r", value = method)
if (p_method != "asymptotic") cs_error("CS_E_INVALID_OPTION", option = "The p-value method", allowed = "large-sample with a nonzero null correlation", value = p_method)
if (n < 4) cs_error("CS_E_TOO_FEW_ROWS", what = "A test against a nonzero null correlation", min = 4, n = n)
zr <- cs_rho0_test(estimate, n, rho0, alternative)
p <- unname(zr[["p"]])
extra <- c(extra, list(rho0 = rho0, z_rho0 = unname(zr[["z"]])))
p_note <- sprintf("Fisher z test against ρ0 = %g", rho0)
}
if (p_method == "exact") {
if (method != "kendall") cs_error("CS_E_INVALID_OPTION", option = "An exact p-value", allowed = "used with Kendall's tau (use the permutation p-value)", value = method)
if (length(unique(x)) < n || length(unique(y)) < n) cs_error("CS_E_INVALID_OPTION", option = "An exact Kendall p-value", allowed = "used without tied values (use the permutation p-value)", value = "tied values")
if (n > 500) cs_error("CS_E_INVALID_OPTION", option = "An exact Kendall p-value", allowed = "used with at most 500 rows", value = sprintf("%d rows", n))
p <- cs_kendall_exact_p(x, y, alternative)$p
p_note <- "exact p-value (no ties)"
} else if (p_method == "permutation") {
n_perm <- as.integer(9999)
seed <- as.integer(1)
perm <- cs_corr_perm_p(x, y, method, alternative, n_perm, seed)
p <- perm$p
extra <- c(extra, list(n_perm = perm$b, perm_count = perm$count))
p_note <- sprintf("permutation p-value (%d permutations, (count + 1) / (B + 1))", perm$b)
}
if (p_method != "asymptotic") extra$p_method <- p_method
# %% Lens: on the Fisher z scale with the coefficient's own SE, bounds atanh'd, interval back-transformed
lens_kind <- "none"
lens <- NULL
if (lens_kind != "none" && !ci_defined) {
warnings <- c(warnings, cs_warning("CS_W_SMALL_SAMPLE", n = n, consequence = "the lens test needs a confidence interval and is not reported."))
} else if (lens_kind != "none") {
lens_low <- NULL
lens_high <- NULL
for (bound in list(lens_low, lens_high)) if (!is.null(bound) && !(bound > -1 && bound < 1)) stop("Lens bounds for a correlation must lie strictly between −1 and 1.")
se_z <- switch(method, pearson = 1 / sqrt(n - 3), spearman = sqrt((1 + estimate^2 / 2) / (n - 3)), kendall = sqrt(0.437 / (n - 4)))
lens <- cs_lens(lens_kind, atanh(estimate), se_z, NULL, if (is.null(lens_low)) NULL else atanh(lens_low),
if (is.null(lens_high)) NULL else atanh(lens_high), 1 - conf)
lens$lens_ci_low <- tanh(lens$lens_ci_low)
lens$lens_ci_high <- tanh(lens$lens_ci_high)
}
# %% Assumptions
zx <- (x - mean(x)) / sd(x)
zy <- (y - mean(y)) / sd(y)
n_outliers <- sum(abs(zx) > 3.29 | abs(zy) > 3.29)
if (method == "pearson") {
out_status <- if (n_outliers > 0) "warn" else "pass"
out_detail <- if (n_outliers > 0) sprintf("%d point(s) more than 3.29 SD from a mean can dominate Pearson's r; compare with Spearman's ρ.", n_outliers)
else "No point is more than 3.29 SD from either mean."
} else {
out_status <- "info"
out_detail <- sprintf("%d point(s) more than 3.29 SD from a mean; rank correlations are robust to them.", n_outliers)
}
# %% Result
alpha <- 1 - conf
pct <- sprintf("%.0f%%", conf * 100)
size <- magnitude(estimate, c(0.1, 0.3, 0.5))
significance <- if (p < alpha) {
sprintf("The association is statistically significant (%s).", cs_fmt_p(p))
} else {
sprintf("The data are compatible with no association (%s).", cs_fmt_p(p))
}
label <- c(pearson = "Pearson correlation", spearman = "Spearman rank correlation", kendall = "Kendall's tau-b")[[method]]
ci_text <- if (!is.null(ci_low)) sprintf(", %s CI [%.2f, %.2f]", pct, ci_low, ci_high) else ""
summary <- sprintf("%s and %s show a %s %s %s association (%s = %.2f%s, n = %d). %s",
a, b, size, if (estimate > 0) "positive" else "negative", if (method == "pearson") "linear" else "monotonic",
symbol, estimate, ci_text, n, significance)
if (!is.null(lens)) summary <- paste(summary, sprintf("Lens (%s): %s (%s).", gsub("_", " ", lens_kind), lens$lens_verdict, cs_fmt_p(lens$lens_p)))
ci_apa <- if (!is.null(ci_low)) {
sprintf(", %s CI [%s, %s]", pct, cs_fmt_num(ci_low, leading_zero = FALSE), cs_fmt_num(ci_high, leading_zero = FALSE))
} else {
""
}
apa <- if (!is.null(dof)) {
sprintf("%s(%d) = %s, %s%s", symbol, dof, cs_fmt_num(estimate, leading_zero = FALSE), cs_fmt_p(p), ci_apa)
} else {
sprintf("%s = %s, %s, N = %d", symbol, cs_fmt_num(estimate, leading_zero = FALSE), cs_fmt_p(p), n)
}
chart_rows <- unique(round(seq(1, n, length.out = min(n, 5000))))
cs_publish(list(
method = "correlation.test",
methodVersion = "1.2.0",
title = label,
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = apa,
statistics = list(
list(key = "estimate", label = symbol, value = estimate),
list(key = "p", label = "p", value = p, format = "p"),
list(key = "ci", label = paste(pct, "CI"), value = c(ci_low, ci_high)),
list(key = "n", label = "n", value = n)
) |> c(if (!is.null(lens)) list(list(key = "lens_p", label = sprintf("Lens p (%s)", gsub("_", " ", lens_kind)), value = lens$lens_p, format = "p")) else list()),
tables = list(),
effectSizes = list(list(key = "estimate", label = symbol, value = estimate, ciLow = ci_low, ciHigh = ci_high, ciLevel = conf,
method = ci_note, magnitude = size, ruleSet = "Cohen (1988), r")),
assumptions = list(list(key = "form", label = if (method == "pearson") "Linear relationship" else "Monotonic relationship", status = "info",
detail = "Check a scatter plot: correlation coefficients summarize only this kind of association."),
list(key = "outliers", label = "Outlying points", status = out_status, statistic = n_outliers, detail = out_detail)),
charts = list(cs_chart("scatter", "scatter", sprintf("%s against %s", b, a), list(x = cs_col(a, x[chart_rows]), y = cs_col(b, y[chart_rows])))),
warnings = warnings,
notes = c(list(sprintf("%s; alternative: %s; %s.", label, alternative, p_note)),
if (!is.null(lens)) list(sprintf("The lens interval [%.3g, %.3g] is the %.0f%% Fisher z interval for %s.", lens$lens_ci_low, lens$lens_ci_high, (1 - 2 * (1 - conf)) * 100, symbol)) else list()),
values = c(list(estimate = estimate, p = p, ci_low = ci_low, ci_high = ci_high, n = n, t = t, df = dof, method = method, n_outliers = n_outliers), lens, extra)
))
Sources
- Bonett, D. G., & Wright, T. A. (2000). Sample size requirements for estimating Pearson, Kendall and Spearman correlations. Psychometrika, 65, 23–28.
- Fieller, E. C., Hartley, H. O., & Pearson, E. S. (1957). Tests for rank correlation coefficients. I. Biometrika, 44, 470–481.
From the CodeSplash method registry · correlation.test v1.2.0.