Skip to content

CAssociation · correlation.matrix

Correlation matrix (Pearson / Spearman / Kendall)

How strongly do several numeric variables move together, pair by pair?

Every pairwise correlation among 2–30 numeric variables with Fisher-z intervals and p-values adjusted for the number of pairs (Holm by default, or Benjamini–Hochberg for exploratory screens). Missing values are handled pairwise or listwise.

Verified in Python and R Python and R agree to 10 decimals

A real result

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

Pearson correlation matrixRecorded · Python and R agreeRecorded 2026-11-17 · 45 values compared
R

mpg and weight (1000 lbs): r = −.87, adjusted p < .001

Pairs
6
Significant (holm)
5

Plots

r between every pairWhat do the values of a square or rectangular result matrix look like at a glance?
View data
Variable labelVariabler
mpgmpg1
weight (1000 lbs)−.87*mpg−0.8677
hp−.78*mpg−0.7762
qsec.42*mpg0.4187
mpg−.87*weight (1000 lbs)−0.8677
weight (1000 lbs)weight (1000 lbs)1
hp.66*weight (1000 lbs)0.6587
qsec−.17weight (1000 lbs)−0.1747
mpg−.78*hp−0.7762
weight (1000 lbs).66*hp0.6587
hphp1
qsec−.71*hp−0.7082
mpg.42*qsec0.4187
weight (1000 lbs)−.17qsec−0.1747
hp−.71*qsec−0.7082
qsecqsec1

Assumptions

  • Linear relationships — Coefficients summarize only this kind of association; check scatter plots of the strongest pairs.
  • Rows per pair — Every pair has at least 10 complete rows (smallest n = 32).

Pairwise correlations

Variable 1Variable 2nr95% CI low95% CI highpp (holm)
mpgweight (1000 lbs)32−0.8677−0.9338−0.7441< .001< .001
mpghp32−0.7762−0.8853−0.5861< .001< .001
mpgqsec320.41870.08200.6696.017.034
weight (1000 lbs)hp320.65870.40250.8193< .001< .001
weight (1000 lbs)qsec32−0.1747−0.49340.1853.339.339
hpqsec32−0.7082−0.8476−0.4774< .001< .001

Correlation matrix (r)

mpgweight (1000 lbs)hpqsec
mpg1−0.8677−0.77620.4187
weight (1000 lbs)−0.867710.6587−0.1747
hp−0.77620.65871−0.7082
qsec0.4187−0.1747−0.70821
  • Pairwise deletion; two-sided tests; holm adjustment over 6 pairs; * = adjusted p < 0.05.
Python

mpg and weight (1000 lbs): r = −.87, adjusted p < .001

Pairs
6
Significant (holm)
5

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

Assumptions

  • Linear relationships — Coefficients summarize only this kind of association; check scatter plots of the strongest pairs.
  • Rows per pair — Every pair has at least 10 complete rows (smallest n = 32).

Pairwise correlations

Variable 1Variable 2nr95% CI low95% CI highpp (holm)
mpgweight (1000 lbs)32−0.8677−0.9338−0.7441< .001< .001
mpghp32−0.7762−0.8853−0.5861< .001< .001
mpgqsec320.41870.08200.6696.017.034
weight (1000 lbs)hp320.65870.40250.8193< .001< .001
weight (1000 lbs)qsec32−0.1747−0.49340.1853.339.339
hpqsec32−0.7082−0.8476−0.4774< .001< .001

Correlation matrix (r)

mpgweight (1000 lbs)hpqsec
mpg1−0.8677−0.77620.4187
weight (1000 lbs)−0.867710.6587−0.1747
hp−0.77620.65871−0.7082
qsec0.4187−0.1747−0.70821
  • Pairwise deletion; two-sided tests; holm adjustment over 6 pairs; * = adjusted p < 0.05.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Pearson holmmtcars · variables: mpg, weight (1000 lbs), hp, qsec
  • Spearman bh pairwise missingairquality · variables: Ozone, Solar.R, Wind, Temp
  • Kendall listwiseairquality · variables: Ozone, Solar.R, Temp
  • Two variablesiris · variables: Sepal.Length, Sepal.Width
  • Degenerate constantmtcars · variables: mpg, weight (1000 lbs), hp, qsec
  • Degenerate infmtcars · variables: mpg, weight (1000 lbs), hp, qsec
  • Degenerate all namtcars · variables: mpg, weight (1000 lbs), hp, qsec
  • Degenerate n2mtcars · variables: mpg, weight (1000 lbs), hp, qsec

In the guides

Tests from the statistics guide this method runs

Where it sits in the decision guides

  • Continuous–continuous: Pearson / Spearman / Kendall · Statistics Guide · C — Test association
  • Monotonic / non-parametric / nominal relationships · Statistics Guide · C — Test association
  • Multiple comparisons · Statistics Guide · Additional considerations
  • EDA (correlation, distributions) · DS & ML Decision Guide · Describe — summarize and visualize
  • Correlation analysis (Pearson, Spearman) · DS & ML Decision Guide · Explain — why is it happening?

What you need

Variablesnumeric · 2–30 columns
Each pair of these variables is correlated.

Choices you make

statistics

Coefficientdefault pearson

Pearson measures straight-line association; Spearman and Kendall use ranks, so they tolerate outliers and curves.

  • Pearson r (linear)(default) — Measures straight-line association on raw values; pick it for roughly linear relationships without outliers.
  • Spearman ρ (ranks) — Correlates ranks; pick it for monotonic curves or outliers.
  • Kendall τ_b (ranks, ties) — Counts concordant pairs, adjusted for ties; pick it for small samples or many ties.

posthoc

p-value adjustmentdefault holm

The family is all pairs in this matrix. Holm controls the chance of any false positive; BH the expected share of false positives (better for exploratory screens).

  • Holm (family-wise)(default) — Controls the chance of any false positive and always finds at least as much as Bonferroni; a good default.
  • Benjamini–Hochberg (false discovery rate) — Controls the expected share of false positives among the findings; pick it when screening many comparisons.
  • Bonferroni — Multiplies each p by the number of tests; the plainest and strictest control, best for a few comparisons.
  • Hochberg — A step-up version of Holm that finds a little more; valid when the tests are independent or positively correlated.
  • Benjamini–Yekutieli — A stricter Benjamini–Hochberg that holds under any dependence; pick it when tests may be negatively correlated.
  • None — Reports raw p-values; use it for one planned comparison, or say plainly that the results are exploratory.

options

Missing valuesdefault pairwise

Pairwise keeps the most data per pair; listwise uses the same complete rows for every pair (consistent but fewer rows).

  • Pairwise (each pair uses its complete rows)(default) — Each pair uses every row complete for those two columns; keeps more data, but matrix entries rest on different rows.
  • Listwise (rows complete on every variable) — Uses only rows complete on every variable; all correlations rest on the same rows, with fewer of them.

hypothesis

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Linear (Pearson) or monotonic (rank) relationships

  • Rows per pair

    Pairs with fewer than 10 complete rows give unstable estimates.

What it reports

n
How many independent units the analysis used; it sets precision and power.
n_pairs
How many independent units the analysis used; it sets precision and power.
n_significant
How many independent units the analysis used; it sets precision and power.
strongest_pair
The two variables with the largest absolute correlation in the matrix, written as 'A and B'.
strongest_r
A number from −1 to 1 for how closely two variables move together; Pearson measures straight-line association.
strongest_p_adj
How surprising your data would be if the null hypothesis were true, as a probability.
max_abs_r
A number from −1 to 1 for how closely two variables move together; Pearson measures straight-line association.
method
The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
adjust
Running many tests raises the chance that at least one is a false positive.

Per group, level or term: r[<a>|<b>], p[…], p_adj[…], ci_low[…], ci_high[…], n[…]

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Same conventions as correlation.test: asymptotic p-values for Spearman and Kendall in both engines.
Python

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

# Correlation matrix (Pearson / Spearman / Kendall)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.matrix 1.0.1 · spec 1efaf86cc5080e08
# 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

import codesplash as cs
from codesplash.stats import correlation as cscor
from codesplash.stats.padjust import p_adjust

# %% Data
variables = ["mpg", "weight (1000 lbs)", "hp", "qsec"]
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=variables)
n_input = len(df)
missing = "pairwise"  # pairwise | listwise
warnings = []
for v in variables:
    if n_input and df[v].isna().all():
        cs.cs_error("CS_E_ALL_MISSING", column=v)
if missing == "listwise":
    df = df.dropna(subset=variables)  # rows complete on every variable
    if n_input - len(df):
        warnings.append(f"{n_input - len(df)} of {n_input} rows were left out because a value was missing.")
    if n_input and not len(df):
        cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, variables)  # infinite values stop the run (registry/errors.yaml)

# %% Correlations
method = "pearson"
adjust = "holm"
conf = 0.95
pairs = []
for i in range(len(variables)):
    for j in range(i + 1, len(variables)):
        a, b = variables[i], variables[j]
        d = df[[a, b]].dropna()  # pairwise complete rows (all rows when listwise)
        cs.check_rows(len(d), 3, f"The correlation of {a} and {b}")
        for col in (a, b):
            if d[col].nunique() < 2:  # r = 0 / 0
                cs.cs_error("CS_E_CONSTANT", column=col)
        res = cscor.pair_test(d[a].to_numpy(dtype=float), d[b].to_numpy(dtype=float), method, "two-sided", conf)
        pairs.append({"a": a, "b": b, **res})
p_adj = p_adjust([r["p"] for r in pairs], adjust)  # the family: every pair in this matrix
for r, q in zip(pairs, p_adj):
    r["p_adj"] = float(q)

# %% Result
alpha = 1 - conf
symbol = {"pearson": "r", "spearman": "ρ", "kendall": "τ_b"}[method]
best = max(pairs, key=lambda r: abs(r["estimate"]))
n_sig = sum(r["p_adj"] < alpha for r in pairs)
small = [f"{r['a']} – {r['b']}" for r in pairs if r["n"] < 10]
values = {"n": len(df) if missing == "listwise" else n_input, "n_pairs": len(pairs), "n_significant": n_sig,
          "strongest_pair": f"{best['a']} and {best['b']}", "strongest_r": best["estimate"], "strongest_p_adj": best["p_adj"],
          "max_abs_r": abs(best["estimate"]), "method": method, "adjust": adjust}
for r in pairs:
    key = f"{r['a']}|{r['b']}"
    values.update({f"r[{key}]": r["estimate"], f"p[{key}]": r["p"], f"p_adj[{key}]": r["p_adj"],
                   f"ci_low[{key}]": r["ci_low"], f"ci_high[{key}]": r["ci_high"], f"n[{key}]": r["n"]})
lookup = {(r["a"], r["b"]): r for r in pairs} | {(r["b"], r["a"]): r for r in pairs}
cells_row, cells_col, cells_val, cells_label = [], [], [], []
for a in variables:
    for b in variables:
        r = lookup.get((a, b))
        cells_row.append(a)
        cells_col.append(b)
        cells_val.append(1.0 if r is None else r["estimate"])
        cells_label.append("" if r is None else f"{cs.fmt_num(r['estimate'], leading_zero=False)}{'*' if r['p_adj'] < alpha else ''}")
summary = (
    f"Of {len(pairs)} pairs, {n_sig} {'is' if n_sig == 1 else 'are'} significant after {adjust} adjustment; the strongest association is between "
    f"{best['a']} and {best['b']} ({symbol} = {best['estimate']:.2f}, adjusted {cs.fmt_p(best['p_adj'])})."
)
cs.publish({
    "method": "correlation.matrix",
    "methodVersion": "1.0.1",
    "title": {"pearson": "Pearson", "spearman": "Spearman", "kendall": "Kendall"}[method] + " correlation matrix",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": values["n"],
    "summary": summary,
    "apa": f"{best['a']} and {best['b']}: {symbol} = {cs.fmt_num(best['estimate'], leading_zero=False)}, adjusted {cs.fmt_p(best['p_adj'])}",
    "statistics": [{"key": "n_pairs", "label": "Pairs", "value": len(pairs), "format": "integer"},
                   {"key": "n_significant", "label": f"Significant ({adjust})", "value": n_sig, "format": "integer"}],
    "tables": [
        {"key": "pairs", "title": "Pairwise correlations", "columns": [
            {"key": "a", "label": "Variable 1", "type": "string"}, {"key": "b", "label": "Variable 2", "type": "string"},
            {"key": "n", "label": "n", "type": "integer"}, {"key": "estimate", "label": symbol, "type": "number"},
            {"key": "ci_low", "label": f"{conf:.0%} CI low", "type": "number"}, {"key": "ci_high", "label": f"{conf:.0%} CI high", "type": "number"},
            {"key": "p", "label": "p", "type": "pvalue"}, {"key": "p_adj", "label": f"p ({adjust})", "type": "pvalue"}],
         "rows": [{k: v for k, v in r.items() if k != "df"} for r in pairs]},
        {"key": "matrix", "title": f"Correlation matrix ({symbol})", "columns": [{"key": "variable", "label": "", "type": "string"}]
         + [{"key": v, "label": v, "type": "number"} for v in variables],
         "rows": [{"variable": a, **{b: (1.0 if a == b else lookup[(a, b)]["estimate"]) for b in variables}} for a in variables]},
    ],
    "effectSizes": [],
    "assumptions": [
        {"key": "form", "label": "Linear relationships" if method == "pearson" else "Monotonic relationships", "status": "info",
         "detail": "Coefficients summarize only this kind of association; check scatter plots of the strongest pairs."},
        {"key": "sample_size", "label": "Rows per pair", "status": "warn" if small else "pass",
         "detail": f"Fewer than 10 complete rows: {', '.join(small)}." if small else f"Every pair has at least 10 complete rows (smallest n = {min(r['n'] for r in pairs)})."},
    ],
    "warnings": warnings,
    "notes": [f"{missing.capitalize()} deletion; two-sided tests; {adjust} adjustment over {len(pairs)} pairs; * = adjusted p < {alpha:g}."],
    "charts": [cs.chart("matrix", "matrix-heatmap", f"{symbol} between every pair", {
        "row": cs.col("Variable", cells_row, levels=variables), "col": cs.col("Variable ", cells_col, levels=variables),
        "value": cs.col(symbol, cells_val), "label": cs.col("label", cells_label, kind="categorical")},
        controls={"scale": "diverging", "min": -1, "max": 1})],
    "values": values,
})
R

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

# Correlation matrix (Pearson / Spearman / Kendall)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.matrix 1.0.1 · spec 1efaf86cc5080e08
# 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
variables <- c("mpg", "weight (1000 lbs)", "hp", "qsec")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mtcars.parquet", col_select = variables))
n_input <- nrow(df)
missing <- "pairwise"  # pairwise | listwise
warnings <- list()
for (v in variables) {
  if (n_input > 0 && all(is.na(df[[v]]))) cs_error("CS_E_ALL_MISSING", column = v)
}
if (missing == "listwise") {
  df <- df[stats::complete.cases(df[variables]), , drop = FALSE]  # rows complete on every variable
  if (n_input - nrow(df) > 0) warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - nrow(df), n_input))
  if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
}
cs_check_finite_columns(df, variables)  # infinite values stop the run (registry/errors.yaml)

# %% Correlations
method <- "pearson"
adjust <- "holm"
conf <- 0.95
pairs <- list()
for (i in seq_along(variables)) {
  for (j in seq_along(variables)) {
    if (j <= i) next
    a <- variables[i]
    b <- variables[j]
    d <- df[stats::complete.cases(df[c(a, b)]), c(a, b)]  # pairwise complete rows (all rows when listwise)
    cs_check_rows(nrow(d), 3, sprintf("The correlation of %s and %s", a, b))
    for (col in c(a, b)) {
      if (length(unique(d[[col]])) < 2) cs_error("CS_E_CONSTANT", column = col)  # r = 0 / 0
    }
    res <- cs_cor_pair(d[[a]], d[[b]], method, "two-sided", conf)
    pairs[[length(pairs) + 1]] <- c(list(a = a, b = b), res)
  }
}
p_adj <- cs_p_adjust(vapply(pairs, `[[`, 0, "p"), adjust)  # the family: every pair in this matrix
for (i in seq_along(pairs)) pairs[[i]]$p_adj <- p_adj[i]

# %% Result
alpha <- 1 - conf
symbol <- c(pearson = "r", spearman = "ρ", kendall = "τ_b")[[method]]
best <- pairs[[which.max(abs(vapply(pairs, `[[`, 0, "estimate")))]]
n_sig <- sum(vapply(pairs, `[[`, 0, "p_adj") < alpha)
small <- vapply(Filter(function(r) r$n < 10, pairs), function(r) paste(r$a, "–", r$b), "")
n_used <- if (missing == "listwise") nrow(df) else n_input
values <- list(n = n_used, n_pairs = length(pairs), n_significant = n_sig, strongest_pair = paste(best$a, "and", best$b),
               strongest_r = best$estimate, strongest_p_adj = best$p_adj, max_abs_r = abs(best$estimate), method = method, adjust = adjust)
for (r in pairs) {
  key <- paste0(r$a, "|", r$b)
  values[[sprintf("r[%s]", key)]] <- r$estimate
  values[[sprintf("p[%s]", key)]] <- r$p
  values[[sprintf("p_adj[%s]", key)]] <- r$p_adj
  values[sprintf("ci_low[%s]", key)] <- list(r$ci_low)  # list(): an empty interval stays as null
  values[sprintf("ci_high[%s]", key)] <- list(r$ci_high)
  values[[sprintf("n[%s]", key)]] <- r$n
}
find <- function(a, b) {
  for (r in pairs) if ((r$a == a && r$b == b) || (r$a == b && r$b == a)) return(r)
  NULL
}
cells <- expand.grid(col = variables, row = variables, stringsAsFactors = FALSE)[, c("row", "col")]
cells_val <- numeric(nrow(cells))
cells_label <- character(nrow(cells))
for (i in seq_len(nrow(cells))) {
  r <- find(cells$row[i], cells$col[i])
  cells_val[i] <- if (is.null(r)) 1 else r$estimate
  cells_label[i] <- if (is.null(r)) "" else paste0(cs_fmt_num(r$estimate, leading_zero = FALSE), if (r$p_adj < alpha) "*" else "")
}
matrix_rows <- lapply(variables, function(a) {
  row <- list(variable = a)
  for (b in variables) row[[b]] <- if (a == b) 1 else find(a, b)$estimate
  row
})
summary <- sprintf("Of %d pairs, %d %s significant after %s adjustment; the strongest association is between %s and %s (%s = %.2f, adjusted %s).",
                   length(pairs), n_sig, if (n_sig == 1) "is" else "are", adjust, best$a, best$b, symbol, best$estimate, cs_fmt_p(best$p_adj))
pct <- sprintf("%.0f%%", conf * 100)
cs_publish(list(
  method = "correlation.matrix",
  methodVersion = "1.0.1",
  title = paste(c(pearson = "Pearson", spearman = "Spearman", kendall = "Kendall")[[method]], "correlation matrix"),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n_used,
  summary = summary,
  apa = sprintf("%s and %s: %s = %s, adjusted %s", best$a, best$b, symbol, cs_fmt_num(best$estimate, leading_zero = FALSE), cs_fmt_p(best$p_adj)),
  statistics = list(list(key = "n_pairs", label = "Pairs", value = length(pairs), format = "integer"),
                    list(key = "n_significant", label = sprintf("Significant (%s)", adjust), value = n_sig, format = "integer")),
  tables = list(
    list(key = "pairs", title = "Pairwise correlations", columns = list(
      list(key = "a", label = "Variable 1", type = "string"), list(key = "b", label = "Variable 2", type = "string"),
      list(key = "n", label = "n", type = "integer"), list(key = "estimate", label = symbol, type = "number"),
      list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"),
      list(key = "p", label = "p", type = "pvalue"), list(key = "p_adj", label = sprintf("p (%s)", adjust), type = "pvalue")),
      rows = lapply(pairs, function(r) r[names(r) != "df"])),
    list(key = "matrix", title = sprintf("Correlation matrix (%s)", symbol),
         columns = c(list(list(key = "variable", label = "", type = "string")), lapply(variables, function(v) list(key = v, label = v, type = "number"))),
         rows = matrix_rows)
  ),
  effectSizes = list(),
  assumptions = list(
    list(key = "form", label = if (method == "pearson") "Linear relationships" else "Monotonic relationships", status = "info",
         detail = "Coefficients summarize only this kind of association; check scatter plots of the strongest pairs."),
    list(key = "sample_size", label = "Rows per pair", status = if (length(small)) "warn" else "pass",
         detail = if (length(small)) sprintf("Fewer than 10 complete rows: %s.", paste(small, collapse = ", "))
                  else sprintf("Every pair has at least 10 complete rows (smallest n = %d).", min(vapply(pairs, `[[`, 0, "n"))))
  ),
  warnings = warnings,
  notes = list(sprintf("%s deletion; two-sided tests; %s adjustment over %d pairs; * = adjusted p < %s.",
                       paste0(toupper(substr(missing, 1, 1)), substr(missing, 2, nchar(missing))), adjust, length(pairs), format(alpha))),
  charts = list(cs_chart("matrix", "matrix-heatmap", sprintf("%s between every pair", symbol), list(
    row = cs_col("Variable", cells$row, levels = variables), col = cs_col("Variable ", cells$col, levels = variables),
    value = cs_col(symbol, cells_val), label = cs_col("label", cells_label, kind = "categorical")),
    controls = list(scale = "diverging", min = -1, max = 1))),
  values = values
))

Sources

  • Holm, S. (1979). A simple sequentially rejective multiple test procedure. Scandinavian Journal of Statistics, 6, 65–70.
  • Benjamini, Y., & Hochberg, Y. (1995). Controlling the false discovery rate. JRSS B, 57, 289–300.

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