如何计算R中不同列维的矩阵之间的相关性

时间:2014-11-21 01:32:24

标签: r matrix

我有两个具有相同行数和不同列数的矩阵:

mat1 <- matrix(rnorm(20), 4, 5)
mat2 <- matrix(rnorm(12), 4, 3)

由于我有相同的行数,我想计算矩阵列之间的以下相关性:

 cor.test(mat1[,1], mat2[,1])
 cor.test(mat1[,1], mat2[,2])
 cor.test(mat1[,1], mat2[,3])
 cor.test(mat1[,2], mat2[,1])
 cor.test(mat1[,2], mat2[,2])
 cor.test(mat1[,2], mat2[,3])
 ...........
 ...........
 cor.test(mat1[,5], mat2[,3])

for(i in 1:5){
  for(j in 1:3){
    pv[i,j] <- cor.test(mat1[, i], mat2[ , j])$p.value
  }
}

最后我想要一个包含相关值的矩阵(5 * 3)或向量,有人可以帮忙吗?

我可以用它来返回p.value和估计吗?

 FUN <- function(x, y) { 
    res <- cor.test(x, y, method="spearman", exact=F) 
    return(list(c = res$estimate, p = res$p.value)) 
  }

 r1 <- outer(colnames(mat1), colnames(mat2), Vectorize(function(i,j) FUN(mat1[,i], mat2[,j])$p))
 r2 <- outer(colnames(mat1), colnames(mat2), Vectorize(function(i,j) FUN(mat1[,i], mat2[,j])$c))

谢谢。

5 个答案:

答案 0 :(得分:3)

为什么不用cor函数来计算皮尔森相关性?

seed(1)
mat1 <- matrix(rnorm(20), 4, 5)
mat2 <- matrix(rnorm(12), 4, 3)
cor(mat1, mat2)
       [,1]        [,2]        [,3]
[1,]  0.4406765 -0.70959590  0.10731768
[2,] -0.2566199 -0.01588993 -0.63630159
[3,] -0.9813313  0.85082165 -0.77172317
[4,]  0.6121358 -0.38564314  0.87077092
[5,] -0.6897573  0.66272015 -0.08380553

要仔细检查,

> col_1 <- 3
> col_2 <- 2
# all.equal is used to compare numeric equality where `==` is discouraged
> all.equal(cor(mat1, mat2)[col_1, col_2], cor(mat1[,col_1], mat2[,col_2]))
[1] TRUE

他们是平等的!

答案 1 :(得分:1)

另一种选择,比我认为的循环更容易理解:

sapply(
  data.frame(mat1),
  function(x) Map(function(a,b) cor.test(a,b)$p.value,
                                list(x),
                                as.data.frame(mat2))
)

结果:

#     X1        X2        X3        X4        X5       
#[1,] 0.7400541 0.8000358 0.5084979 0.4441933 0.9104712
#[2,] 0.2918163 0.2764817 0.956807  0.6072979 0.4395218
#[3,] 0.2866105 0.4095909 0.5648188 0.1746428 0.9125866

答案 2 :(得分:0)

我认为你需要的只是先定义你的矩阵

mat_cor <- matrix(nrow=ncol(mat1), ncol=ncol(mat2))
for(i in 1:5)
    {
        for(j in 1:3)
            {
                mat_cor[i,j] <- cor.test(mat1[, i], mat2[ , j])$p.value
            }
    }

输出

mat_cor

          [,1]      [,2]        [,3]
[1,] 0.9455569 0.8362242 0.162569342
[2,] 0.7755360 0.9849619 0.775006329
[3,] 0.8799139 0.8050564 0.001358697
[4,] 0.1574388 0.1808167 0.618624825
[5,] 0.8571844 0.8897125 0.879818822

答案 3 :(得分:0)

我想你不想这样做。有了基础的东西,这里是双重申请方法:

apply(mat1, 2, function(col_mat1){
  apply(mat2, 2, function(col2, col1) {
    cor.test(col2, col1)$p.value
  }, col1=col_mat1)
})

outter apply在mat1列进行迭代,并为cor.test()的一侧提供服务。内在的一样,但现在填充cor.test()的第二面。在实践中,申请正在取代for。

答案 4 :(得分:0)

你可以试试这样的东西

pv <- c()
for(i in 1:dim(mat1)[2]){
  for(j in 1:dim(mat2)[2]){
    pv <-c(c, cor.test(mat1[, i], mat2[ , j])$estimate)
  }
}

dim(pv) <- c(dim(mat1)[2], dim(mat2)[2])
相关问题