Pairwise partial correlation of a matrix controlled by one variable
I have a 100 column table for which I would like to perform pairwise partial correlations by manipulating the 100th column variable using a function pcor.test
from the package ppcor
. Is there some kind of partial correlation function in R so that I can use the return values, for example rcorr
, taking pairwise correlations of the entire matrix, but controlling only one variable?
source to share
It looks like, for an n-column matrix, you want to output the (n-1) x (n-1) matrix of pairwise correlations of the first n-1 columns, driving the latter (using pcor.test
from the package ppcor
).
You can do this with a function sapply
, looping through each column and calculating its correlation with all other columns with pcor.test
:
# Sample dataset with 5 columns
set.seed(144)
dat <- matrix(rnorm(1000), ncol=5)
# Compute the 4x4 correlation matrix, controlling for the fifth column
library(ppcor)
sapply(1:(ncol(dat)-1), function(x) sapply(1:(ncol(dat)-1), function(y) {
if (x == y) 1
else pcor.test(dat[,x], dat[,y], dat[,ncol(dat)])$estimate
}))
# [,1] [,2] [,3] [,4]
# [1,] 1.000000000 -0.01885158 0.06037621 0.004032437
# [2,] -0.018851576 1.00000000 0.09560611 0.097152907
# [3,] 0.060376208 0.09560611 1.00000000 0.105123093
# [4,] 0.004032437 0.09715291 0.10512309 1.000000000
source to share