Skip to content

Spearman and Kendall: correlation on ranks

When a relationship is monotonic rather than straight, or outliers dominate, rank coefficients ask a different and often better question.

Introductory ~11 min10 steps

What runs in CodeSplash

You will be able to

  • Explain what "monotonic" means and why ranks capture it
  • Compute how Spearman's rho relates to Pearson's r on ranks
  • Read Kendall's tau as a difference between concordant and discordant pairs
  • Compare Pearson, Spearman and Kendall on the same data without expecting equal numbers

Read first

01

Ozone rises faster than a straight line

Read

In New York's 1973 airquality readings, ozone stays low on cool days and climbs steeply on hot ones. That shape is monotonic: as temperature rises, ozone tends to rise too, but not at a constant rate.

Pearson's r rewards straight lines, so a curve like this costs it points. Ranks don't care about the shape of the rise, only about its direction.

New York air quality, 1973
02

Replace values with ranks

Explore

Sort a column and replace each value with its position: smallest becomes 1, next becomes 2, and so on. Equal values share the average of their positions.

BExplorable · What ranks throw away

What changes when a test uses ranks instead of the values?

If the largest value became ten times larger, what would the Mann–Whitney p-value do?

How sure?
1.00
12
0
valuesranks
Testp
t test on values.009
Mann–Whitney.007
t test on ranks.005

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Stretch the largest value as far as you like. Its rank stays the same, which is why rank methods shrug off extreme values.

03

Spearman is Pearson on ranks

Read

Spearman's rhoSpearman correlationPearson correlation of the ranks; captures any steadily rising or falling relationship and resists outliers. is Pearson's r computed on the ranks of each variable. It equals +1+1 when one variable always rises with the other, whatever the curve looks like.

When there are no ties, it has a short formula, where did_i is the difference between a row's two ranks:

ρ=1−6∑idi2n(n2−1)\rho = 1 - \frac{6\sum_i d_i^2}{n(n^2-1)}
04

Kendall counts pairs

Read

Kendall's tauKendall's tauA rank correlation from the balance of concordant and discordant pairs; robust with ties and small samples. looks at every pair of rows. A pair is concordant when the row higher on xx is also higher on yy, and discordant when it is lower.

τ=concordant−discordantnumber of pairs\tau = \frac{\text{concordant} - \text{discordant}}{\text{number of pairs}}

That reading is direct: tau is how much more likely a random pair is to agree than to disagree. CodeSplash reports τb\tau_b, which adjusts the denominator for ties.

05

Three numbers for one pair

Predict

Predict first

Ozone and temperature, three ways: Pearson, Spearman, Kendall. Which do you expect to be smallest?

Kendall is smallestSpearman is smallestAll three are equal
Reveal

Pearson r = 0.698, Spearman ρ = 0.774, Kendall τ = 0.586. Spearman beats Pearson because the rise is curved. Kendall is on a smaller scale by construction: for moderate relationships it usually runs at roughly two-thirds to three-quarters of Spearman. Never compare a tau directly with an r.

06

Read the result

In the app
Kendall's tau-bRecorded · Python and R agreeRecorded 2026-11-21 · 9 values compared
R

τ_b = .59, p < .001, N = 116

τ_b
0.5863
p
< .001
90% CI
[0.5148, 0.6497]
n
116

Effect size

  • τ_b 0.5863 90% CI [0.5148, 0.6497] · large

Plots

Temp against OzoneHow do two numeric variables move together?
View data
OzoneTemp
4167
3672
1274
1862
2866
2365
1959
861
774
1669
1166
1468
1858
1464
3466
657
3068
1162
159
1173
461
3261
2367
4581
11579
3776
2982
7190
3987
2382
2177
3772
2065
1273
1376
13584
4985
3281
6483
4083
7788
9792
9792
8589
1073
2781
780
4881
3582
6184
7987
6385
1674
8086
10885
2082
5286
8288
5086
6483

First 60 of 116 rows.

Assumptions

  • Monotonic relationship — Check a scatter plot: correlation coefficients summarize only this kind of association.
  • Outlying points — 1 point(s) more than 3.29 SD from a mean; rank correlations are robust to them.
  • 37 of 153 rows were left out because a value was missing.
  • Kendall's tau-b; 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 d7ab5f56b72efd93
# Dataset: airquality (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/airquality.parquet", col_select = c("Ozone", "Temp")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("Ozone", "Temp")]), , 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("Ozone", "Temp"))  # 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 <- "Ozone"
b <- "Temp"
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 <- "kendall"
alternative <- "two-sided"
conf <- 0.9
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)
))
Python

τ_b = .59, p < .001, N = 116

τ_b
0.5863
p
< .001
90% CI
[0.5148, 0.6497]
n
116

Effect size

  • τ_b 0.5863 90% CI [0.5148, 0.6497] · large

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

Assumptions

  • Monotonic relationship — Check a scatter plot: correlation coefficients summarize only this kind of association.
  • Outlying points — 1 point(s) more than 3.29 SD from a mean; rank correlations are robust to them.
  • 37 of 153 rows were left out because a value was missing.
  • Kendall's tau-b; 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 d7ab5f56b72efd93
# Dataset: airquality (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/airquality.parquet", columns=["Ozone", "Temp"])
n_input = len(df)
df = df.dropna(subset=["Ozone", "Temp"])  # 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, ["Ozone", "Temp"])  # 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 = "Ozone", "Temp"
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 = "kendall"
alternative = "two-sided"
conf = 0.9
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 card reports τ with its interval on the 116 complete pairs. Rows missing either value are dropped, and the card tells you how many rows it used.

Rank tests still assume independent rows. They relax the shape of the relationship, not the design of the study.

07

Exact and permutation p-values

Read

The rank p-values above lean on a large-sample approximation. With few rows, ask for a p-value that doesn't:

  • Exact (Kendall, no ties) counts every ordering of the rows: with n rows there are n! of them, and the share with at least as many concordant pairs is the p-value.
  • Permutation shuffles one variable thousands of times and counts how often the shuffled coefficient is as extreme as yours. It works for all three coefficients and with ties; the p-value is (count + 1) / (B + 1).
Kendall's tau-bRecorded · Python and R agreeRecorded 2026-11-21 · 10 values compared
R

τ_b = .11, p = .065, N = 120

τ_b
0.1140
p
.065
95% CI
[−0.0058, 0.2306]
n
120

Effect size

  • τ_b 0.1140 95% CI [−0.0058, 0.2306] · small

Plots

y noise against x2How do two numeric variables move together?
View data
x2y noise
1.9060.9621
2.132−0.1781
0.23150.0033
0.89690.5116
−1.739−0.4561
0.4688−0.2109
−0.5441−0.5726
−0.1654−0.3533
0.5522−1.050
1.0330.7884
−0.04620.6192
2.639−0.7858
0.58901.782
−0.2024−0.2499
0.4416−0.3011
−0.1003−1.499
−1.0930.0342
0.5032−0.9110
0.94920.3514
0.38280.1954
0.37160.8596
0.1572−0.6742
0.8479−1.663
−1.2830.3900
1.1580.4414
−0.90911.284
0.3350−0.1632
0.77590.4996
0.23710.4601
−1.560−0.4763
0.0243−1.557
0.3346−0.6890
0.98940.1484
0.50040.1354
0.5769−1.372
1.143−0.0931
−0.7074−1.118
−0.61860.7448
−0.00830.0777
0.3389−0.4999
1.4050.6117
−0.8653−0.8690
−0.87401.166
0.7743−0.7697
−0.4019−1.807
−0.2151−0.9175
0.6053−0.3565
−0.6146−0.1766
−0.7244−0.7993
−0.2569−0.3928
−0.39210.2737
−0.68670.2581
0.87580.1104
−0.4811−0.9152
0.06840.2129
0.13701.403
−1.859−0.8084
0.34631.920
1.5020.8657
−0.0137−1.264

First 60 of 120 rows.

Assumptions

  • Monotonic relationship — Check a scatter plot: correlation coefficients summarize only this kind of association.
  • Outlying points — 0 point(s) more than 3.29 SD from a mean; rank correlations are robust to them.
  • Kendall's tau-b; alternative: two-sided; exact p-value (no ties).
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 12b631bf2f0300c6
# 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("x2", "y noise")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("x2", "y noise")]), , 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("x2", "y noise"))  # 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 <- "x2"
b <- "y noise"
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 <- "kendall"
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 <- "exact"
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)
))
Python

τ_b = .11, p = .065, N = 120

τ_b
0.1140
p
.065
95% CI
[−0.0058, 0.2306]
n
120

Effect size

  • τ_b 0.1140 95% CI [−0.0058, 0.2306] · small

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

Assumptions

  • Monotonic relationship — Check a scatter plot: correlation coefficients summarize only this kind of association.
  • Outlying points — 0 point(s) more than 3.29 SD from a mean; rank correlations are robust to them.
  • Kendall's tau-b; alternative: two-sided; exact p-value (no ties).
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 12b631bf2f0300c6
# 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

# %% Data
df = pd.read_parquet("tests/parity/fixtures/f_dependence.parquet", columns=["x2", "y noise"])
n_input = len(df)
df = df.dropna(subset=["x2", "y noise"])  # 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, ["x2", "y noise"])  # 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 = "x2", "y noise"
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 = "kendall"
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 = "exact"
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},
})

Here the exact p and the large-sample p are close because there are 120 rows. Below about 20 rows they can differ a lot.

08

Check your understanding

Checkpoint

Check yourself

For which relationship would Spearman's rho equal exactly 1 while Pearson's r stays below 1?

Show the answer

Answer: a

y = exp(x) always rises, so its ranks agree perfectly, but the curve isn't a straight line. y = x² on a symmetric range rises and falls, so it isn't monotonic. y = 2x + 1 gives 1 for both.

Check yourself

Among all pairs in a dataset with no ties, 75% are concordant and 25% discordant. What is Kendall's tau?

Show the answer

Answer: 0.5

Tau is the concordant share minus the discordant share: 0.75 − 0.25 = 0.5.

Check yourself

You multiply the largest value of x by 100. Which coefficient changes most?

Show the answer

Answer: a

The point keeps the same rank, so Spearman and Kendall don't change at all. Pearson's r uses the values themselves, so it can move a lot.

Check yourself

Your data have several tied values in x. Which p-value can you still ask for besides the large-sample one?

Show the answer

Answer: b

The exact Kendall distribution assumes no ties, so CodeSplash stops and suggests the permutation p, which shuffles the observed values, ties included.

09

Do it on your own data

In the app

Set Coefficient to Spearman or Kendall in the correlation test. Kendall is the better choice when you have many ties, such as Likert-style scores or rounded measurements.

Python
import pandas as pd
from scipy import stats

df = pd.read_csv("airquality.csv").dropna(subset=["Ozone", "Temp"])
print(stats.spearmanr(df["Ozone"], df["Temp"]))
# tau-b; method="asymptotic" matches R's exact = FALSE (the default "auto" may pick an exact p)
print(stats.kendalltau(df["Ozone"], df["Temp"], method="asymptotic"))
R
df <- read.csv("airquality.csv")
cor.test(df$Ozone, df$Temp, method = "spearman", exact = FALSE)
cor.test(df$Ozone, df$Temp, method = "kendall", exact = FALSE)

Notebook exercise · ~8 min

Rank correlations in code

Compute Spearman's rho and Kendall's tau-b for ozone and temperature, after dealing with the missing days.

  1. Spearman's rho

    Store Spearman's rank correlation between ozone and temperature in rho. Use ozone and temp, which hold only the days where both were measured; if you start from df, drop the missing days yourself.

    Show a solution
    Python
    rho = stats.spearmanr(ozone, temp).statistic
    R
    rho <- cor(ozone, temp, method = "spearman")
  2. Kendall's tau-b

    Store Kendall's tau-b (the version that adjusts for ties) in tau.

    Show a solution
    Python
    tau = stats.kendalltau(ozone, temp).statistic
    R
    tau <- cor(ozone, temp, method = "kendall")

In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.

10

Recap

Recap
  • Ranks measure monotonic relationships and resist extreme values.
  • Spearman's rho is Pearson's r on ranks; Kendall's tau compares concordant and discordant pairs.
  • The three coefficients are on different scales: report which one you used and don't compare across them.
  • Independence of rows is still required.