Skip to content

Is one correlation stronger than another?

Two correlations can look different and not be. Match the test to the design, independent groups or the same rows, and read the interval for the difference.

Applied ~11 min9 steps

What runs in CodeSplash

You will be able to

  • Recognize the three designs for comparing correlations
  • Use Fisher's z test for correlations from independent groups
  • Use Williams or Steiger when correlations share rows
  • Report the difference with Zou's interval and Cohen's q

Read first

01

The tempting wrong answer

Read

Maternal age and birth weight correlate at 0.20 among non-smokers and −0.14 among smokers.

It's tempting to test each one against zero, see that one "works" and one doesn't, and declare them different. But a difference between significant and non-significant isn't itself necessarily significant. You have to test the difference directly.

02

Which design do you have?

Reflect

The right test depends on where the two correlations come from:

  • Independent: different rows, as with two separate groups. Fisher's zz test.
  • Overlapping: the same rows, one variable shared. Is mileage closer to weight or to horsepower? Williams' test or Steiger's.
  • Non-overlapping: the same rows, four different variables. Steiger's test.

Think of a comparison you might make in your own work. Which of the three is it?

03

Independent groups

Read

Correlations aren't normally distributed, especially near ±1. Fisher's zFisher z transformationatanh(r) — turns a correlation into a nearly normal quantity with standard error 1/√(n − 3). transform fixes that, and each zz has variance 1/(n−3)1/(n-3):

z=12ln⁡1+r1−r,Z=z1−z21n1−3+1n2−3z = \tfrac12 \ln\frac{1+r}{1-r}, \qquad Z = \frac{z_1 - z_2}{\sqrt{\tfrac{1}{n_1-3} + \tfrac{1}{n_2-3}}}

For the smokers comparison, ZZ = 2.30, p = .021. The interval for the difference runs from 0.05 to 0.62.

04

Make a prediction

Predict

Predict first

On the same 32 cars, mileage correlates −0.87 with weight and −0.78 with horsepower. Weight and horsepower correlate 0.66 with each other.

Is weight the stronger correlate of mileage?

Yes, clearlyNo, the data are compatible with no differenceCan't be tested
Reveal

Williams' test gives p = .188. With this many cars, the data are compatible with no difference, and the interval for the difference runs from −0.27 to 0.04.

05

Why shared rows need a different test

Read

When correlations come from the same rows, they move together: a sample that happens to inflate one tends to inflate the other. Fisher's test would ignore that link.

Williams' tt and Steiger's ZZ build the correlation between the two estimates into the standard error, using the third correlation ryzr_{yz}. For four separate variables on the same rows, Steiger's test uses all six correlations. On mtcars, comparing mileage–weight with displacement–quarter-mile time gives p < .001.

06

Read the card

In the app
Comparing independent correlationsRecorded · Python and R agreeRecorded 2026-11-17 · 17 values compared
R

z = 2.30, p = .021, Δr = .35, 95% CI [.05, .62], q = 0.35

r₁
0.2015
r₂
−0.1442
r₁ − r₂
0.3456
z
2.303
p
.021
95% CI (Zou)
[0.0510, 0.6206]

Effect size

  • Cohen's q 0.3494
  • r₁ − r₂ 0.3456 95% CI [0.0510, 0.6206]

Assumptions

  • Approximately bivariate normal data — Fisher-z based tests assume normal variables; check scatter plots for curvature and outliers.
  • Valid correlation matrix — Independent samples: each correlation comes from its own group.

All applicable tests

TestStatisticdfp
Fisher r-to-z2.303—.021
  • Pearson correlations; Fisher r-to-z; alternative: two-sided; Zou's (2007) two-sided 95% interval for r₁ − r₂.
The exact R script · R R version 4.5.1 (2025-06-13)
# Compare two correlations (Fisher z, Williams, Steiger)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.compare 1.0.1 · spec b09c691cef35475a
# Dataset: birthwt (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/birthwt.parquet", col_select = c("age", "bwt", "smoke")))
n_input <- nrow(df)
df[["smoke"]] <- factor(df[["smoke"]], levels = c("false", "true"))  # stored level order
df <- df[stats::complete.cases(df[c("age", "bwt", "smoke")]), , 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("age", "bwt", "smoke"))  # infinite values stop the run (registry/errors.yaml)

# %% Correlations
a <- "age"
b <- "bwt"
c3 <- NULL
d4 <- NULL
g <- "smoke"
alternative <- "two-sided"
conf <- 0.95
test <- "fisher"
r_of <- function(u, v) stats::cor(as.double(u), as.double(v))

if (!is.null(g) && !is.null(c3)) stop("Bind either Two independent groups or a Third variable, not both.")
if (!is.null(d4) && is.null(c3)) stop("Non-overlapping correlations need a Third variable as well as the Fourth.")
r_yz <- NULL; n1 <- NULL; n2 <- NULL; level_1 <- NULL; level_2 <- NULL
# Fisher's z and the tests for correlations from one sample have SE terms in 1 / (n - 3).
if (!is.null(g)) {
  lv <- levels(df[[g]])
  if (length(lv) != 2) cs_error("CS_E_GROUP_COUNT", column = g, expected = 2, k = length(lv))
  for (l in lv) {
    if (sum(df[[g]] == l) < 4) cs_error("CS_E_SMALL_GROUP", min = 4, group = l, n = sum(df[[g]] == l))
  }
} else if (!is.null(c3) && nrow(df) < 4) {
  cs_error("CS_E_TOO_FEW_ROWS", what = "Comparing correlations", min = 4, n = nrow(df))
}
# A correlation is 0 / 0 when one of its variables is constant.
for (col in c(a, b, c3, d4)) {
  if (length(unique(df[[col]])) < 2) cs_error("CS_E_CONSTANT", column = col)
}
if (!is.null(g)) {
  design <- "independent"
  boolean_group <- TRUE
  level_1 <- if (boolean_group) sprintf("%s = %s", g, lv[1]) else lv[1]
  level_2 <- if (boolean_group) sprintf("%s = %s", g, lv[2]) else lv[2]
  d1 <- df[df[[g]] == lv[1], , drop = FALSE]
  d2 <- df[df[[g]] == lv[2], , drop = FALSE]
  n1 <- nrow(d1); n2 <- nrow(d2)
  for (part in list(list(label = level_1, d = d1), list(label = level_2, d = d2))) {
    for (col in c(a, b)) {
      if (length(unique(part$d[[col]])) < 2) {
        cs_error("CS_E_UNDEFINED", what = sprintf("The correlation of %s and %s in %s", a, b, part$label),
                 reason = sprintf("%s has no variation in this group", col))
      }
    }
  }
  r1 <- r_of(d1[[a]], d1[[b]]); r2 <- r_of(d2[[a]], d2[[b]])
  res <- cs_cor_compare_independent(r1, n1, r2, n2, alternative = alternative, conf = conf)
  allowed <- "fisher"
} else if (!is.null(c3) && is.null(d4)) {
  design <- "overlapping"
  r1 <- r_of(df[[a]], df[[b]]); r2 <- r_of(df[[a]], df[[c3]]); r_yz <- r_of(df[[b]], df[[c3]])
  res <- cs_cor_compare_overlapping(r1, r2, r_yz, nrow(df), alternative = alternative, conf = conf)
  allowed <- c("williams", "steiger", "hittner")
} else if (!is.null(c3)) {
  design <- "nonoverlapping"
  rr <- list(xy = r_of(df[[a]], df[[b]]), zw = r_of(df[[c3]], df[[d4]]), xz = r_of(df[[a]], df[[c3]]), xw = r_of(df[[a]], df[[d4]]),
             yz = r_of(df[[b]], df[[c3]]), yw = r_of(df[[b]], df[[d4]]))
  r1 <- rr$xy; r2 <- rr$zw
  res <- cs_cor_compare_nonoverlapping(rr, nrow(df), alternative = alternative, conf = conf)
  allowed <- "steiger"
} else {
  stop("Bind Two independent groups (independent samples) or a Third variable (one sample).")
}
n <- nrow(df)
if (test == "auto") test <- allowed[1]
if (!(test %in% allowed)) stop(sprintf("The %s test does not apply to %s correlations; choose one of: %s.", test, design, paste(allowed, collapse = ", ")))
main <- Filter(function(t) t$test == test, res$tests)[[1]]
statistic <- main$statistic; dof <- main$df; p <- main$p

# %% Result
alpha <- 1 - conf
pct <- sprintf("%.0f%%", conf * 100)
first <- if (design == "independent") {
  sprintf("r(%s, %s) = %.2f in %s (n = %d) and %.2f in %s (n = %d)", a, b, r1, level_1, n1, r2, level_2, n2)
} else if (design == "overlapping") {
  sprintf("%s correlated r = %.2f with %s and r = %.2f with %s (n = %d; r(%s, %s) = %.2f)", a, r1, b, r2, c3, n, b, c3, r_yz)
} else {
  sprintf("r(%s, %s) = %.2f and r(%s, %s) = %.2f (n = %d)", a, b, r1, c3, d4, r2, n)
}
verdict <- if (p < alpha) sprintf("The correlations differ (%s).", cs_fmt_p(p)) else sprintf("The data are compatible with equal correlations (%s).", cs_fmt_p(p))
summary <- sprintf("%s: a difference of %.2f, %s CI [%.2f, %.2f]. %s", first, res$diff, pct, res$ci_low, res$ci_high, verdict)
stat_txt <- if (!is.null(dof)) sprintf("t(%s) = %.2f", format(dof), statistic) else sprintf("z = %.2f", statistic)
apa <- sprintf("%s, %s, Δr = %s, %s CI [%s, %s], q = %.2f", stat_txt, cs_fmt_p(p), cs_fmt_num(res$diff, leading_zero = FALSE), pct,
               cs_fmt_num(res$ci_low, leading_zero = FALSE), cs_fmt_num(res$ci_high, leading_zero = FALSE), res$q)
rows <- lapply(res$tests, function(t) list(test = t$label, statistic = t$statistic, df = t$df, p = t$p))
cs_publish(list(
  method = "correlation.compare",
  methodVersion = "1.0.1",
  title = c(independent = "Comparing independent correlations", overlapping = "Comparing overlapping correlations",
            nonoverlapping = "Comparing non-overlapping correlations")[[design]],
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = apa,
  statistics = list(
    list(key = "r1", label = "r₁", value = r1),
    list(key = "r2", label = "r₂", value = r2),
    list(key = "diff", label = "r₁ − r₂", value = res$diff),
    list(key = "statistic", label = if (!is.null(dof)) "t" else "z", value = statistic),
    list(key = "p", label = "p", value = p, format = "p"),
    list(key = "ci", label = sprintf("%s CI (Zou)", pct), value = c(res$ci_low, res$ci_high))
  ),
  tables = list(list(key = "tests", title = "All applicable tests", columns = list(
    list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
    list(key = "df", label = "df", type = "number"), list(key = "p", label = "p", type = "pvalue")), rows = rows)),
  effectSizes = list(list(key = "q", label = "Cohen's q", value = res$q, method = "atanh(r₁) − atanh(r₂)"),
                     list(key = "diff", label = "r₁ − r₂", value = res$diff, ciLow = res$ci_low, ciHigh = res$ci_high,
                          ciLevel = conf, method = "Zou (2007) interval")),
  assumptions = list(
    list(key = "normality", label = "Approximately bivariate normal data", status = "info",
         detail = "Fisher-z based tests assume normal variables; check scatter plots for curvature and outliers."),
    list(key = "matrix", label = "Valid correlation matrix", status = "pass",
         detail = if (design != "independent") "The correlations form a valid (positive definite) correlation matrix."
                  else "Independent samples: each correlation comes from its own group.")
  ),
  charts = list(),
  warnings = warnings,
  notes = list(sprintf("Pearson correlations; %s; alternative: %s; Zou's (2007) two-sided %s interval for r₁ − r₂.", main$label, alternative, pct)),
  values = list(design = design, test = test, r1 = r1, r2 = r2, r_yz = r_yz, n = n, n1 = n1, n2 = n2, diff = res$diff,
                statistic = statistic, df = dof, p = p, ci_low = res$ci_low, ci_high = res$ci_high, q = res$q,
                level_1 = level_1, level_2 = level_2)
))
Python

z = 2.30, p = .021, Δr = .35, 95% CI [.05, .62], q = 0.35

r₁
0.2015
r₂
−0.1442
r₁ − r₂
0.3456
z
2.303
p
.021
95% CI (Zou)
[0.0510, 0.6206]

Effect size

  • Cohen's q 0.3494
  • r₁ − r₂ 0.3456 95% CI [0.0510, 0.6206]

Assumptions

  • Approximately bivariate normal data — Fisher-z based tests assume normal variables; check scatter plots for curvature and outliers.
  • Valid correlation matrix — Independent samples: each correlation comes from its own group.

All applicable tests

TestStatisticdfp
Fisher r-to-z2.303—.021
  • Pearson correlations; Fisher r-to-z; alternative: two-sided; Zou's (2007) two-sided 95% interval for r₁ − r₂.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Compare two correlations (Fisher z, Williams, Steiger)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.compare 1.0.1 · spec b09c691cef35475a
# Dataset: birthwt (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 dependence

# %% Data
df = pd.read_parquet("tests/parity/fixtures/birthwt.parquet", columns=["age", "bwt", "smoke"])
n_input = len(df)
df["smoke"] = pd.Categorical(df["smoke"], categories=["false", "true"])  # stored level order
df = df.dropna(subset=["age", "bwt", "smoke"])  # listwise deletion over the analysis columns
df["smoke"] = df["smoke"].cat.remove_unused_categories()
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, ["age", "bwt", "smoke"])  # infinite values stop the run (registry/errors.yaml)

# %% Correlations
a, b = "age", "bwt"
c = None
d = None
g = "smoke"
alternative = "two-sided"
conf = 0.95
test = "fisher"


def r_of(u, v):
    return float(np.corrcoef(u.to_numpy(dtype=float), v.to_numpy(dtype=float))[0, 1])


if g is not None and c is not None:
    raise ValueError("Bind either Two independent groups or a Third variable, not both.")
if d is not None and c is None:
    raise ValueError("Non-overlapping correlations need a Third variable as well as the Fourth.")
r_yz = n1 = n2 = level_1 = level_2 = None
# Fisher's z and the tests for correlations from one sample have SE terms in 1 / (n − 3).
if g is not None:
    levels = list(df[g].cat.categories)
    if len(levels) != 2:
        cs.cs_error("CS_E_GROUP_COUNT", column=g, expected=2, k=len(levels))
    for lv in levels:
        if (df[g] == lv).sum() < 4:
            cs.cs_error("CS_E_SMALL_GROUP", min=4, group=str(lv), n=int((df[g] == lv).sum()))
elif c is not None and len(df) < 4:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Comparing correlations", min=4, n=len(df))
# A correlation is 0 / 0 when one of its variables is constant.
for col in [v for v in (a, b, c, d) if v is not None]:
    if df[col].nunique() < 2:
        cs.cs_error("CS_E_CONSTANT", column=col)
if g is not None:
    design = "independent"
    boolean_group = True
    level_1, level_2 = ((f"{g} = {levels[0]}", f"{g} = {levels[1]}") if boolean_group else (str(levels[0]), str(levels[1])))
    d1, d2 = df[df[g] == levels[0]], df[df[g] == levels[1]]
    n1, n2 = len(d1), len(d2)
    for label, part in ((level_1, d1), (level_2, d2)):
        for col in (a, b):
            if part[col].nunique() < 2:
                cs.cs_error("CS_E_UNDEFINED", what=f"The correlation of {a} and {b} in {label}", reason=f"{col} has no variation in this group")
    r1, r2 = r_of(d1[a], d1[b]), r_of(d2[a], d2[b])
    res = dependence.compare_independent(r1, n1, r2, n2, alternative=alternative, conf=conf)
    allowed = ["fisher"]
elif c is not None and d is None:
    design = "overlapping"
    r1, r2, r_yz = r_of(df[a], df[b]), r_of(df[a], df[c]), r_of(df[b], df[c])
    res = dependence.compare_overlapping(r1, r2, r_yz, len(df), alternative=alternative, conf=conf)
    allowed = ["williams", "steiger", "hittner"]
elif c is not None:
    design = "nonoverlapping"
    r = {"xy": r_of(df[a], df[b]), "zw": r_of(df[c], df[d]), "xz": r_of(df[a], df[c]), "xw": r_of(df[a], df[d]),
         "yz": r_of(df[b], df[c]), "yw": r_of(df[b], df[d])}
    r1, r2 = r["xy"], r["zw"]
    res = dependence.compare_nonoverlapping(r, len(df), alternative=alternative, conf=conf)
    allowed = ["steiger"]
else:
    raise ValueError("Bind Two independent groups (independent samples) or a Third variable (one sample).")
n = len(df)
if test == "auto":
    test = allowed[0]
if test not in allowed:
    raise ValueError(f"The {test} test does not apply to {design} correlations; choose one of: {', '.join(allowed)}.")
main = next(t for t in res["tests"] if t["test"] == test)
statistic, dof, p = main["statistic"], main["df"], main["p"]

# %% Result
alpha = 1 - conf
pct = f"{conf:.0%}"
if design == "independent":
    first = f"r({a}, {b}) = {r1:.2f} in {level_1} (n = {n1}) and {r2:.2f} in {level_2} (n = {n2})"
elif design == "overlapping":
    first = f"{a} correlated r = {r1:.2f} with {b} and r = {r2:.2f} with {c} (n = {n}; r({b}, {c}) = {r_yz:.2f})"
else:
    first = f"r({a}, {b}) = {r1:.2f} and r({c}, {d}) = {r2:.2f} (n = {n})"
verdict = (f"The correlations differ ({cs.fmt_p(p)})." if p < alpha
           else f"The data are compatible with equal correlations ({cs.fmt_p(p)}).")
summary = f"{first}: a difference of {res['diff']:.2f}, {pct} CI [{res['ci_low']:.2f}, {res['ci_high']:.2f}]. {verdict}"
stat_txt = f"t({dof:g}) = {statistic:.2f}" if dof is not None else f"z = {statistic:.2f}"
apa = (f"{stat_txt}, {cs.fmt_p(p)}, Δr = {cs.fmt_num(res['diff'], leading_zero=False)}, {pct} CI "
       f"[{cs.fmt_num(res['ci_low'], leading_zero=False)}, {cs.fmt_num(res['ci_high'], leading_zero=False)}], q = {res['q']:.2f}")
rows = [{"test": t["label"], "statistic": t["statistic"], "df": t["df"], "p": t["p"]} for t in res["tests"]]
cs.publish({
    "method": "correlation.compare",
    "methodVersion": "1.0.1",
    "title": {"independent": "Comparing independent correlations", "overlapping": "Comparing overlapping correlations",
              "nonoverlapping": "Comparing non-overlapping correlations"}[design],
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": apa,
    "statistics": [
        {"key": "r1", "label": "r₁", "value": r1},
        {"key": "r2", "label": "r₂", "value": r2},
        {"key": "diff", "label": "r₁ − r₂", "value": res["diff"]},
        {"key": "statistic", "label": "t" if dof is not None else "z", "value": statistic},
        {"key": "p", "label": "p", "value": p, "format": "p"},
        {"key": "ci", "label": f"{pct} CI (Zou)", "value": [res["ci_low"], res["ci_high"]]},
    ],
    "tables": [{"key": "tests", "title": "All applicable tests", "columns": [
        {"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
        {"key": "df", "label": "df", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}], "rows": rows}],
    "effectSizes": [{"key": "q", "label": "Cohen's q", "value": res["q"], "method": "atanh(r₁) − atanh(r₂)"},
                    {"key": "diff", "label": "r₁ − r₂", "value": res["diff"], "ciLow": res["ci_low"], "ciHigh": res["ci_high"],
                     "ciLevel": conf, "method": "Zou (2007) interval"}],
    "assumptions": [
        {"key": "normality", "label": "Approximately bivariate normal data", "status": "info",
         "detail": "Fisher-z based tests assume normal variables; check scatter plots for curvature and outliers."},
        {"key": "matrix", "label": "Valid correlation matrix", "status": "pass",
         "detail": "The correlations form a valid (positive definite) correlation matrix." if design != "independent"
         else "Independent samples: each correlation comes from its own group."},
    ],
    "charts": [],
    "warnings": warnings,
    "notes": [f"Pearson correlations; {main['label']}; alternative: {alternative}; Zou's (2007) two-sided {pct} interval for r₁ − r₂."],
    "values": {"design": design, "test": test, "r1": r1, "r2": r2, "r_yz": r_yz, "n": n, "n1": n1, "n2": n2,
               "diff": res["diff"], "statistic": statistic, "df": dof, "p": p, "ci_low": res["ci_low"], "ci_high": res["ci_high"],
               "q": res["q"], "level_1": level_1, "level_2": level_2},
})

Besides the pp-value, the card reports the difference with Zou's interval and Cohen's q, the difference on the zz scale: here 0.35. Cohen's conventions call qq of 0.10.1, 0.30.3 and 0.50.5 small, medium and large; use them only when you have nothing better.

07

Check your understanding

Checkpoint

Check yourself

You ask 200 employees about pay, satisfaction and tenure. Is satisfaction more strongly related to pay or to tenure? Which test fits?

Show the answer

Answer: b

Same rows, one shared variable (satisfaction): that's the overlapping design.

Check yourself

In women, r = .40 (p = .01). In men, r = .25 (p = .09). What can you conclude?

Show the answer

Answer: b

The gap between "significant" and "not significant" is not itself a test. Compare the correlations directly and read the interval.

Check yourself

A correlation comes from 103 rows. What is the variance of its Fisher z? Give the decimal.

Show the answer

Answer: 0.01

The variance is 1/(n − 3) = 1/100 = 0.01.

08

Do it on your own data

In the app

Choose your variables: a group column gives the independent design, a third variable gives the overlapping design, and a fourth gives the non-overlapping one.

Python
import numpy as np
from scipy import stats

r1, n1, r2, n2 = 0.40, 80, 0.25, 90  # independent groups
z = (np.arctanh(r1) - np.arctanh(r2)) / np.sqrt(1 / (n1 - 3) + 1 / (n2 - 3))
print(z, 2 * stats.norm.sf(abs(z)))
R
r1 <- 0.40; n1 <- 80; r2 <- 0.25; n2 <- 90  # independent groups
z <- (atanh(r1) - atanh(r2)) / sqrt(1 / (n1 - 3) + 1 / (n2 - 3))
c(z = z, p = 2 * pnorm(-abs(z)))
09

Recap

Recap
  • Test the difference between correlations directly; never compare their p-values.
  • Independent groups use Fisher's zz; shared rows use Williams or Steiger, which account for how the correlations move together.
  • Report the difference, its interval, and Cohen's qq.

Concepts in this lesson