Pairwise partial correlation of a matrix, controlling by one variable

纵然是瞬间 提交于 2021-02-19 03:57:07

问题


I have a 100-column table for which I would like to run pairwise partial correlations, controlling by the 100th column's variable using the pcor.test function from the ppcor package. Is there any partial correlation function in R that I can use the returns something like rcorr, taking the pairwise correlations of the whole matrix but only controlling by one variable?


回答1:


It sounds like for an n-column matrix you want to output a (n-1) x (n-1) matrix of the pairwise correlations of the first n-1 columns, controlling for the last (using the pcor.test function from the ppcor package).

You could do this with the sapply function, looping through each column and computing its correlation to 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


来源:https://stackoverflow.com/questions/30198968/pairwise-partial-correlation-of-a-matrix-controlling-by-one-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!