Pearson's r: how tightly two numbers line up
Estimate a correlation by eye, then see what r measures, how its test and interval work, and what it leaves out.
What runs in CodeSplash
- STAT077Pearson correlation test Runs in CodeSplash
- Correlation test (Pearson / Spearman / Kendall) Verified in Python and R
You will be able to
- Describe r as the strength and direction of a straight-line relationship
- Read r with its confidence interval and p-value on a result card
- Square r to get the share of variance two variables have in common
- Check the scatterplot before trusting the number
Do heavier cars use more fuel?
ReadThe classic mtcars data records 32 cars from the 1970s. Heavier cars should travel fewer miles per gallon. How tightly do weight and mileage move together?
A Pearson correlationPearson correlationHow closely two numbers follow a straight line, from −1 to 1. Outliers can pull it a long way. answers that with one number between and . The sign gives the direction. The size says how closely the points hug a straight line.
Guess first
PredictPredict first
Picture a scatterplot with weight along the bottom and miles per gallon up the side. The points fall from upper left to lower right in a fairly tight band.
Drag to your guess for r.
Make your guess between -1 and 1 correlation r, then reveal.
Reveal
CodeSplash gets r = −0.868. A strong negative relationship: heavier cars go fewer miles per gallon.
Train your eye
ExplorePeople tend to underestimate correlations in the middle of the range. A few rounds of guessing recalibrates your eye quickly.
CExplorable · Guess the correlation
How well can you read a correlation from a scatter plot?
Guess the correlation r for this cloud.
Adds a single point against the trend.
Your guesses this session will be tallied here.
Commit your prediction above to see the result
Make your prediction to see the result.
Keep going until your guesses land within a tenth or so of the truth. You will read scatterplots faster for the rest of this track.
What r measures
ReadThe top adds up, point by point, whether and sit on the same side of their means. The bottom rescales that total, so units don't matter: pounds or kilograms give the same r.
Because it only looks at straight-line agreement, r can be near zero for a relationship that is strong but curved.
From r to a test
ReadThe test asks whether the data are compatible with a population correlation of zero. It converts r to a statistic with degrees of freedom:
Here t(30) = −9.56, p < .001. The 95% interval, from −0.93 to −0.74, uses the Fisher zFisher z transformationatanh(r) — turns a correlation into a nearly normal quantity with standard error 1/√(n − 3). transform.
Read the card
Readr(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.
The exact R script · R 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)
))
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.
The exact Python script · Python 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},
})
Start with the estimate and its interval: they say how strong the relationship is and how precisely you know it. The p-value only says whether zero is compatible with the data. With a large sample, a tiny and unimportant r can still have a small p-value.
Move a point
ExplorePearson's r is built from squared distances, so one extreme point can drag it a long way.
CExplorable · Drag one point across five correlations
How much can one point move a correlation, and which measures hold steady?
Drag a far-out point into the corner. Which measure moves the most?
Bars show the size of each measure. Drag the red point, or focus it and use the arrow keys.
Commit your prediction above to see the result
Make your prediction to see the result.
Drag a single point far from the cloud and watch r swing. Compare the rank-based coefficients beside it: they move much less. The next lesson explains why.
Testing against a nonzero correlation
ReadThe usual test asks whether r differs from 0. Sometimes 0 is the wrong benchmark: a published study reported a strong negative correlation and you want to know whether your data disagree with it. Set Null correlation ρ0 and CodeSplash tests r against it with Fisher's z: (atanh r − atanh ρ0) × √(n − 3).
r(30) = −.87, p = .014, 95% CI [−.93, −.74]
- r
- −0.8677
- p
- .014
- 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; Fisher z test against ρ0 = -0.7.
The exact R script · R 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 36bbde248a90dafb
# 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.7
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)
))
r(30) = −.87, p = .014, 95% CI [−.93, −.74]
- r
- −0.8677
- p
- .014
- 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; Fisher z test against ρ0 = -0.7.
The exact Python script · Python 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 36bbde248a90dafb
# 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.7
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 interval doesn't change; only the question the p-value answers does.
Check your understanding
CheckpointCheck yourself
For weight and mileage, r = −0.87. What share of the variance in mileage is shared with weight? Answer as a proportion with two decimals.
Show the answer
Answer: 0.75
Square r: 0.87 × 0.87 ≈ 0.75. About three quarters of the variance in mileage is shared with weight, which describes the data and does not show that weight causes it.
Check yourself
You recompute the correlation after converting weight from pounds to kilograms. What happens to r?
Show the answer
Answer: a
Pearson's r standardizes both variables, so any change of units that keeps the order leaves it unchanged.
Check yourself
A study reports r = 0.02 between dose and response. What can you conclude?
Show the answer
Answer: b
Pearson's r only measures straight-line agreement. A U-shaped relationship can have r near zero and still be strong.
Check yourself
With 200,000 rows, r = 0.03 has p < .001. What is the most useful reading?
Show the answer
Answer: b
Large samples detect tiny effects. The p-value says the data are not compatible with zero; r and its interval say how large the relationship is.
Check yourself
You test r = 0.62 (n = 50) against ρ0 = 0.5 and get p = 0.25. What does that say?
Show the answer
Answer: b
The p-value compares r with ρ0 = 0.5, not with 0. A large p means r is within chance of 0.5; it says nothing about zero.
Do it on your own data
In the appIn Analyze, choose the two numeric columns as First variable and Second variable. Pearson is the default coefficient.
import pandas as pd
from scipy import stats
df = pd.read_csv("mtcars.csv")
res = stats.pearsonr(df["wt"], df["mpg"])
print(res.statistic, res.pvalue)
print(res.confidence_interval(confidence_level=0.95))df <- read.csv("mtcars.csv")
cor.test(df$wt, df$mpg, method = "pearson", conf.level = 0.95)Recap
Recap- Pearson's r measures the direction and tightness of a straight-line relationship.
- Report it with its confidence interval; the p-value alone doesn't convey strength.
- is the share of variance the two variables have in common.
- Look at the scatterplot: a curve or one extreme point can make r misleading.
Concepts in this lesson