Skip to content

Partial correlation: holding a third variable fixed

Horsepower and mileage are strongly correlated, but so are horsepower and weight. Partial correlation asks what is left once weight is accounted for.

Applied ~11 min9 steps

What runs in CodeSplash

You will be able to

  • Compute a partial correlation as the correlation of two sets of residuals
  • Distinguish partial from semipartial correlation
  • Read how a correlation shrinks when a covariate is added
  • Avoid treating a partial correlation as a causal effect

Read first

01

Is it the horsepower or the weight?

Read

Powerful cars get poor mileage: the correlation between horsepower and miles per gallon is −0.776.

But powerful cars also tend to be heavy, and heavy cars get poor mileage. Some of that correlation might be weight wearing a horsepower costume. A partial correlationPartial correlationThe correlation between two variables after removing what a third explains from each of them. removes the part of both variables that weight can explain.

02

Predict the shrinkage

Predict

Predict first

Hold weight fixed. What's left of the correlation between horsepower and mileage? Drag to your guess.

Make your guess between -1 and 0 partial r, then reveal.

Reveal

The partial correlation is −0.547, 95% CI −0.75 to −0.24. Smaller, and still compatible only with a negative relationship. Weight accounted for part of the correlation, not all of it.

03

Residualize, then correlate

Explore

Regress xx on the covariate and keep the residuals. Do the same for yy. The partial correlation is the correlation of those two sets of residuals.

CExplorable · Partial correlation is a correlation of residuals

What does it mean to hold a third variable constant, and when does that mislead?

What will the correlation be after adjusting for the third variable?

0.00
How sure?

The third variable is

0.50
0.50
0.00
150

x and y: r = 0.17

After removing z: r = −0.02

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.

Change how strongly the covariate drives each variable and watch the raw correlation and the residual correlation separate.

04

Partial or semipartial?

Read

The difference is which variable gets cleaned:

  • Partial: covariates are removed from both xx and yy. It answers: among cars of equal weight, do horsepower and mileage move together?
  • Semipartial: covariates are removed from xx only. Squared, it's the share of all of yy's variance that xx uniquely adds.

Here the semipartial is −0.272 with p = .139, while the partial has p = .001. They use different denominators, so they differ in size and in their intervals.

05

Read the card

In the app
Partial correlationRecorded · Python and R agreeRecorded 2026-11-17 · 16 values compared
R

partial r(29) = −.55, p = .001, 95% CI [−.75, −.24]

Partial r
−0.5470
p
.001
Semipartial r
−0.2719
Zero-order r
−0.7762

Effect size

  • Partial r −0.5470 95% CI [−0.7550, −0.2390]

Assumptions

  • Linear relationships — Partial correlation removes only the linear part of the covariates' influence.
  • Rows per parameter — 32 rows for 1 covariate column(s).

Correlations

Correlationrtdfp95% CI low95% CI high
Zero-order−0.7762—30< .001——
Partial−0.5470−3.51929.001−0.7550−0.2390
Semipartial (hp residualized)−0.2719−1.52229.139−0.57120.0912
  • Residual method: hp and mpg are each regressed on weight (1000 lbs) (k = 1 design columns); t tests with n − 2 − k = 29 df.
The exact R script · R R version 4.5.1 (2025-06-13)
# Partial and semipartial correlation
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.partial 1.0.1 · spec dc185af8806530e8
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mtcars.parquet", col_select = c("hp", "mpg", "weight (1000 lbs)")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("hp", "mpg", "weight (1000 lbs)")]), , 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("hp", "mpg", "weight (1000 lbs)"))  # infinite values stop the run (registry/errors.yaml)

# %% Partial correlation
a <- "hp"
b <- "mpg"
covariates <- c("weight (1000 lbs)")
method <- "pearson"
conf <- 0.95
data <- df
if (method == "spearman") {
  # Spearman: Pearson on ranks (average ties) of every numeric variable, covariates included
  for (v in c(a, b, covariates)) if (!is.factor(data[[v]])) data[[v]] <- rank(data[[v]], ties.method = "average")
}
for (cv in covariates) {
  if (is.factor(data[[cv]]) && nlevels(data[[cv]]) < 2) cs_error("CS_E_CONSTANT", column = cv)  # one category: nothing to control for
}
Z <- model.matrix(cs_model_formula(NULL, covariates), data = data)  # intercept + covariates (treatment dummies)
x <- data[[a]]
y <- data[[b]]
n <- length(x)
k <- ncol(Z) - 1
if (n - 3 - k < 1) cs_error("CS_E_TOO_FEW_ROWS", what = "Partial correlation", min = k + 4, n = n)  # the interval's SE is 1 / sqrt(n - 3 - k)
if (qr(Z)$rank < ncol(Z)) cs_error("CS_E_COLLINEAR")
for (col in c(a, b)) {
  if (length(unique(data[[col]])) < 2) cs_error("CS_E_CONSTANT", column = col)  # r = 0 / 0
}
res <- cs_partial_cor(x, y, Z, conf)
pr <- res$partial
sr <- res$semi
zero <- cor.test(x, y)
zero_r <- unname(zero$estimate)
zero_p <- zero$p.value

# %% Result
alpha <- 1 - conf
assumptions <- list(
  list(key = "form", label = if (method == "pearson") "Linear relationships" else "Monotonic relationships", status = "info",
       detail = paste0("Partial correlation removes only the linear part of the covariates' influence", if (method == "spearman") " (on ranks)." else ".")),
  list(key = "sample_size", label = "Rows per parameter", status = if (n < 10 * max(k, 1) + 3) "warn" else "pass",
       detail = sprintf("%d rows for %d covariate column(s).", n, k))
)
symbol <- if (method == "pearson") "r" else "ρ"
pct <- sprintf("%.0f%%", conf * 100)
summary <- sprintf("Controlling for %s, the partial correlation between %s and %s is %s = %.2f (%s CI [%.2f, %.2f], %s), compared with %.2f without controls.",
                   paste(covariates, collapse = ", "), a, b, symbol, pr$r, pct, pr$ci_low, pr$ci_high, cs_fmt_p(pr$p), zero_r)
rows <- list(
  list(type = "Zero-order", r = zero_r, t = NULL, df = n - 2, p = zero_p, ci_low = NULL, ci_high = NULL),
  list(type = "Partial", r = pr$r, t = pr$t, df = pr$df, p = pr$p, ci_low = pr$ci_low, ci_high = pr$ci_high),
  list(type = sprintf("Semipartial (%s residualized)", a), r = sr$r, t = sr$t, df = sr$df, p = sr$p, ci_low = sr$ci_low, ci_high = sr$ci_high)
)
cs_publish(list(
  method = "correlation.partial",
  methodVersion = "1.0.1",
  title = paste0("Partial correlation", if (method == "spearman") " (Spearman)" else ""),
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = sprintf("partial %s(%d) = %s, %s, %s CI [%s, %s]", symbol, pr$df, cs_fmt_num(pr$r, leading_zero = FALSE), cs_fmt_p(pr$p), pct,
                cs_fmt_num(pr$ci_low, leading_zero = FALSE), cs_fmt_num(pr$ci_high, leading_zero = FALSE)),
  statistics = list(
    list(key = "partial_r", label = paste("Partial", symbol), value = pr$r),
    list(key = "partial_p", label = "p", value = pr$p, format = "p"),
    list(key = "semi_r", label = paste("Semipartial", symbol), value = sr$r),
    list(key = "zero_r", label = paste("Zero-order", symbol), value = zero_r)
  ),
  tables = list(list(key = "correlations", title = "Correlations", columns = list(
    list(key = "type", label = "Correlation", type = "string"), list(key = "r", label = symbol, type = "number"),
    list(key = "t", label = "t", type = "number"), list(key = "df", label = "df", type = "number"), list(key = "p", label = "p", type = "pvalue"),
    list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
    rows = rows)),
  effectSizes = list(list(key = "partial_r", label = paste("Partial", symbol), value = pr$r, ciLow = pr$ci_low, ciHigh = pr$ci_high,
                          ciLevel = conf, method = sprintf("Fisher z, SE = 1/√(n − 3 − k), k = %d", k))),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Residual method: %s and %s are each regressed on %s (k = %d design columns); t tests with n − 2 − k = %d df.",
                       a, b, paste(covariates, collapse = ", "), k, pr$df)),
  values = list(partial_r = pr$r, partial_t = pr$t, partial_p = pr$p, partial_ci_low = pr$ci_low, partial_ci_high = pr$ci_high,
                semi_r = sr$r, semi_t = sr$t, semi_p = sr$p, semi_ci_low = sr$ci_low, semi_ci_high = sr$ci_high,
                zero_r = zero_r, zero_p = zero_p, n = n, k = k, df = pr$df, missing_share = if (n_input > 0) n_dropped / n_input else 0)
))
Python

partial r(29) = −.55, p = .001, 95% CI [−.75, −.24]

Partial r
−0.5470
p
.001
Semipartial r
−0.2719
Zero-order r
−0.7762

Effect size

  • Partial r −0.5470 95% CI [−0.7550, −0.2390]

Assumptions

  • Linear relationships — Partial correlation removes only the linear part of the covariates' influence.
  • Rows per parameter — 32 rows for 1 covariate column(s).

Correlations

Correlationrtdfp95% CI low95% CI high
Zero-order−0.7762—30< .001——
Partial−0.5470−3.51929.001−0.7550−0.2390
Semipartial (hp residualized)−0.2719−1.52229.139−0.57120.0912
  • Residual method: hp and mpg are each regressed on weight (1000 lbs) (k = 1 design columns); t tests with n − 2 − k = 29 df.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Partial and semipartial correlation
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method correlation.partial 1.0.1 · spec dc185af8806530e8
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.stats import correlation as cscor
from codesplash.stats import regression as csreg

# %% Data
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=["hp", "mpg", "weight (1000 lbs)"])
n_input = len(df)
df = df.dropna(subset=["hp", "mpg", "weight (1000 lbs)"])  # 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, ["hp", "mpg", "weight (1000 lbs)"])  # infinite values stop the run (registry/errors.yaml)

# %% Partial correlation
a, b = "hp", "mpg"
covariates = ["weight (1000 lbs)"]
method = "pearson"
conf = 0.95
data = df.copy()
if method == "spearman":
    # Spearman: Pearson on ranks (average ties) of every numeric variable, covariates included
    for c in [a, b] + covariates:
        if not isinstance(data[c].dtype, pd.CategoricalDtype):
            data[c] = stats.rankdata(data[c].to_numpy(dtype=float), method="average")
for c in covariates:
    if isinstance(data[c].dtype, pd.CategoricalDtype) and len(data[c].cat.categories) < 2:  # one category: nothing to control for
        cs.cs_error("CS_E_CONSTANT", column=c)
Z = csreg.design_matrix(data, covariates).to_numpy()  # intercept + covariates (dummies for categorical)
x = data[a].to_numpy(dtype=float)
y = data[b].to_numpy(dtype=float)
n = len(x)
k = Z.shape[1] - 1
if n - 3 - k < 1:  # the interval's SE is 1 / √(n − 3 − k)
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Partial correlation", min=k + 4, n=n)
if np.linalg.matrix_rank(Z) < Z.shape[1]:
    cs.cs_error("CS_E_COLLINEAR")
for col, v in ((a, x), (b, y)):
    if len(np.unique(v)) < 2:  # r = 0 / 0
        cs.cs_error("CS_E_CONSTANT", column=col)
res = cscor.partial(x, y, Z, conf)
pr, sr = res["partial"], res["semi"]
zero = stats.pearsonr(x, y)
zero_r, zero_p = float(zero.statistic), float(zero.pvalue)

# %% Result
alpha = 1 - conf
assumptions = [
    {"key": "form", "label": "Linear relationships" if method == "pearson" else "Monotonic relationships", "status": "info",
     "detail": "Partial correlation removes only the linear part of the covariates' influence" + (" (on ranks)." if method == "spearman" else ".")},
    {"key": "sample_size", "label": "Rows per parameter", "status": "warn" if n < 10 * max(k, 1) + 3 else "pass",
     "detail": f"{n} rows for {k} covariate column(s)."},
]
symbol = "r" if method == "pearson" else "ρ"
summary = (
    f"Controlling for {', '.join(covariates)}, the partial correlation between {a} and {b} is {symbol} = {pr['r']:.2f} "
    f"({conf:.0%} CI [{pr['ci_low']:.2f}, {pr['ci_high']:.2f}], {cs.fmt_p(pr['p'])}), compared with {zero_r:.2f} without controls."
)
rows = [
    {"type": "Zero-order", "r": zero_r, "t": None, "df": float(n - 2), "p": zero_p, "ci_low": None, "ci_high": None},
    {"type": "Partial", "r": pr["r"], "t": pr["t"], "df": float(pr["df"]), "p": pr["p"], "ci_low": pr["ci_low"], "ci_high": pr["ci_high"]},
    {"type": f"Semipartial ({a} residualized)", "r": sr["r"], "t": sr["t"], "df": float(sr["df"]), "p": sr["p"], "ci_low": sr["ci_low"], "ci_high": sr["ci_high"]},
]
cs.publish({
    "method": "correlation.partial",
    "methodVersion": "1.0.1",
    "title": "Partial correlation" + (" (Spearman)" if method == "spearman" else ""),
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": f"partial {symbol}({pr['df']}) = {cs.fmt_num(pr['r'], leading_zero=False)}, {cs.fmt_p(pr['p'])}, {conf:.0%} CI [{cs.fmt_num(pr['ci_low'], leading_zero=False)}, {cs.fmt_num(pr['ci_high'], leading_zero=False)}]",
    "statistics": [
        {"key": "partial_r", "label": f"Partial {symbol}", "value": pr["r"]},
        {"key": "partial_p", "label": "p", "value": pr["p"], "format": "p"},
        {"key": "semi_r", "label": f"Semipartial {symbol}", "value": sr["r"]},
        {"key": "zero_r", "label": f"Zero-order {symbol}", "value": zero_r},
    ],
    "tables": [{"key": "correlations", "title": "Correlations", "columns": [
        {"key": "type", "label": "Correlation", "type": "string"}, {"key": "r", "label": symbol, "type": "number"},
        {"key": "t", "label": "t", "type": "number"}, {"key": "df", "label": "df", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
        {"key": "ci_low", "label": f"{conf:.0%} CI low", "type": "number"}, {"key": "ci_high", "label": f"{conf:.0%} CI high", "type": "number"}],
        "rows": rows}],
    "effectSizes": [{"key": "partial_r", "label": f"Partial {symbol}", "value": pr["r"], "ciLow": pr["ci_low"], "ciHigh": pr["ci_high"],
                     "ciLevel": conf, "method": f"Fisher z, SE = 1/√(n − 3 − k), k = {k}"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Residual method: {a} and {b} are each regressed on {', '.join(covariates)} (k = {k} design columns); t tests with n − 2 − k = {pr['df']} df."],
    "values": {"partial_r": pr["r"], "partial_t": pr["t"], "partial_p": pr["p"], "partial_ci_low": pr["ci_low"], "partial_ci_high": pr["ci_high"],
               "semi_r": sr["r"], "semi_t": sr["t"], "semi_p": sr["p"], "semi_ci_low": sr["ci_low"], "semi_ci_high": sr["ci_high"],
               "zero_r": zero_r, "zero_p": zero_p, "n": n, "k": k, "df": float(pr["df"]), "missing_share": n_dropped / n_input if n_input else 0.0},
})

The card shows the raw correlation next to the partial and semipartial values, so you can see how much the covariate changed things. The degrees of freedom are n−2−kn - 2 - k, where kk counts the covariates: here 29.

Covariates can be categorical. In iris, sepal and petal length correlate at 0.872; within species, the partial correlation is 0.756.

06

Controlling isn't explaining

Read

Which case applies depends on how the variables are related in the world. No number on the card can tell you that; draw the causal diagram first.

07

Check your understanding

Checkpoint

Check yourself

How do you get a partial correlation between x and y, controlling for z?

Show the answer

Answer: b

Residuals are what's left of each variable after z has explained what it can. Their correlation is the partial correlation.

Check yourself

You have 32 cars and control for 4 covariates. How many degrees of freedom does the partial correlation test have?

Show the answer

Answer: 26

n − 2 − k = 32 − 2 − 4 = 26.

Check yourself

Talent and looks are unrelated among all actors. Among actors who got famous, partly through talent and partly through looks, you control for fame and find a negative partial correlation. Why?

Show the answer

Answer: b

Conditioning on a common effect creates an association between its causes. More adjustment isn't always better.

08

Do it on your own data

In the app

Pick two variables and at least one covariate. Rows missing any of them are dropped, and the card reports how many.

Python
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from scipy import stats

df = pd.read_csv("mtcars.csv")
rx = smf.ols("hp ~ wt", df).fit().resid
ry = smf.ols("mpg ~ wt", df).fit().resid
r = np.corrcoef(rx, ry)[0, 1]

k, n = 1, len(df)
t = r * np.sqrt((n - 2 - k) / (1 - r**2))
p = 2 * stats.t.sf(abs(t), n - 2 - k)
print(r, t, p)
R
df <- read.csv("mtcars.csv")
rx <- resid(lm(hp ~ wt, df))
ry <- resid(lm(mpg ~ wt, df))
r <- cor(rx, ry)

k <- 1; n <- nrow(df)
t <- r * sqrt((n - 2 - k) / (1 - r^2))
c(r = r, t = t, p = 2 * pt(-abs(t), n - 2 - k))
09

Recap

Recap
  • A partial correlation is the correlation of residuals after removing covariates from both variables.
  • A semipartial removes them from xx only, and squares to the variance xx uniquely adds.
  • Adjusting is only right when the covariate is a confounder: decide with a causal diagram, not with the numbers.

Concepts in this lesson