partialCorrelation

Computes the partial correlation between two variables while controlling for one or more confounding variables.

Partial correlation measures the linear association between x and y after removing the effect of the controls variables. This is useful for determining whether an apparent relationship between two variables is genuine or is explained by shared dependence on a third variable.

Uses the precision matrix (inverse correlation matrix) method: builds the Pearson correlation matrix of all variables, inverts it via Gaussian elimination with partial pivoting, and extracts the partial correlation from the precision matrix elements.

When controls is empty, delegates directly to pearsonCorrelation.

Returns Double.NaN for both coefficient and p-value when the correlation matrix is singular (e.g., collinear controls, constant variable, or degenerate input).

Example:

val x = doubleArrayOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
val y = doubleArrayOf(2.1, 4.3, 5.8, 8.2, 9.7, 12.1, 14.0, 16.2, 17.9, 20.1)
val z = doubleArrayOf(1.5, 3.0, 4.5, 6.0, 7.5, 9.0, 10.5, 12.0, 13.5, 15.0)
val result = partialCorrelation(x, y, z)
result.coefficient // partial r between x and y, controlling for z
result.pValue // two-sided p-value
result.n // 10

Return

a CorrelationResult containing the partial correlation coefficient, two-sided p-value, and sample size.

Parameters

x

the first array of observations.

y

the second array of observations, must have the same size as x.

controls

one or more control variables to partial out. Each must have the same size as x. If empty, returns the Pearson correlation between x and y.