CAssociation · correlation.partial
Partial and semipartial correlation
Are two numeric variables still associated once covariates are held constant?
The correlation between x and y after removing what one or more covariates explain (partial r), the semipartial (part) correlation of y with x's unique part, and the zero-order correlation for comparison. Pearson on the values or Spearman on ranks; t tests with n − 2 − k df and Fisher-z intervals.
A real result
Example “Mtcars pearson”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
| Correlation | r | t | df | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| Zero-order | −0.7762 | — | 30 | < .001 | — | — |
| Partial | −0.5470 | −3.519 | 29 | .001 | −0.7550 | −0.2390 |
| Semipartial (hp residualized) | −0.2719 | −1.522 | 29 | .139 | −0.5712 | 0.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.
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
| Correlation | r | t | df | p | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|
| Zero-order | −0.7762 | — | 30 | < .001 | — | — |
| Partial | −0.5470 | −3.519 | 29 | .001 | −0.7550 | −0.2390 |
| Semipartial (hp residualized) | −0.2719 | −1.522 | 29 | .139 | −0.5712 | 0.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.
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
- Mtcars pearsonmtcars · covariates: weight (1000 lbs) · x: hp · y: mpg
- Airquality spearman missingairquality · covariates: Wind, Solar.R · x: Ozone · y: Temp
- Categorical covariateiris · covariates: Species · x: Sepal.Length · y: Petal.Length
- Degenerate constantmtcars · covariates: weight (1000 lbs) · x: hp · y: mpg
- Degenerate n3mtcars · covariates: weight (1000 lbs) · x: hp · y: mpg
- Degenerate single leveliris · covariates: Species · x: Sepal.Length · y: Petal.Length
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
- Control for covariates: partial correlation · Statistics Guide · C — Test association
- Correlation analysis (Pearson, Spearman) · DS & ML Decision Guide · Explain — why is it happening?
What you need
- First variablenumeric · 1 column
- The first numeric variable.
- Second variablenumeric · 1 column
- The second numeric variable.
- Control fornumeric / categorical / boolean · 1–10 columns · 2–30 levels
- Variables held constant. Categorical ones enter as dummy variables.
Choices you make
statistics
- Coefficientdefault pearson
Pearson works on the values; Spearman on their ranks (robust to outliers and monotone curves).
- Pearson (values)(default) — Partial correlation on raw values; pick it when relationships are roughly linear.
- Spearman (ranks of the numeric variables) — Partial correlation on ranks; pick it for monotonic curves or outliers.
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 (Spearman) relationships with the covariates
Rows per parameter
Needs n > k + 3 (k covariate columns); ten or more rows per covariate column is safer.
What it reports
- Tests: Partial correlation
- Tests: Semipartial correlation
- partial_r
- The correlation between two variables after removing what a third explains from each of them.
- partial_t
- An estimate divided by its standard error, compared with a t distribution.
- partial_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- partial_ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- partial_ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- semi_r
- The correlation between two variables after removing what a third explains from each of them.
- semi_t
- An estimate divided by its standard error, compared with a t distribution.
- semi_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- semi_ci_low
- A range of effect values compatible with your data at the chosen confidence level.
- semi_ci_high
- A range of effect values compatible with your data at the chosen confidence level.
- zero_r
- The correlation between two variables after removing what a third explains from each of them.
- zero_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- n
- How many independent units the analysis used; it sets precision and power.
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- df
- How much independent information is left to estimate variability after fitting the model.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
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
- Residuals by least squares in both engines (numpy lstsq / R lm.fit); ranks with average ties (scipy rankdata / R rank).
The exact script CodeSplash ran for example “Mtcars pearson” · 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 exact script CodeSplash ran for example “Mtcars pearson” · 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)
))
Sources
- Cohen, J., Cohen, P., West, S. G., & Aiken, L. S. (2003). Applied multiple regression/correlation analysis for the behavioral sciences (3rd ed.).
- Kim, S. (2015). ppcor: An R package for a fast calculation to semi-partial correlation coefficients. Communications for Statistical Applications and Methods, 22, 665–674.
From the CodeSplash method registry · correlation.partial v1.0.1.