Skip to content

Efficient calculation of partial correlations in R

2 messages · Schragi Schwartz, John Fox

#
Dear Schragi,

There's a function named partial.cor() in the Rcmdr package, but it's so
simple that I'll just reproduce it here:

partial.cor <- function (X, ...) 
{
    R <- cor(X, ...)
    RI <- solve(R)
    D <- 1/sqrt(diag(RI))
    R <- -RI * (D %o% D)
    diag(R) <- 0
    rownames(R) <- colnames(R) <- colnames(X)
    R
}

Of course, this gives you the partial correlation between each pair of
variables controlling for all others, which is I assume what you want.

I hope this helps,
 John
On
correlations.
http://www.R-project.org/posting-guide.html