不同维度的两个矩阵之间的相关性

时间:2021-05-18 09:28:07

标签: r correlation

我对 R 很陌生。我有两个不同维度的矩阵,C(3 行,79 列)和 T(3 行,215 列)。我希望我的代码计算 C 的第一列和 T 的所有列之间的 Spearman 相关性,并返回与索引和列的最大相关性。然后,C 的第二列和 T 的所有列等等。事实上,我想找到两个矩阵之间最相关的列。希望很清楚。 我所做的是一个嵌套的 for 循环,但结果不是我搜索的。

for (i in 1:79){
    for(j in 1:215){
        print(max(cor(C[,i],T[,j],method = c("spearman"))))
  }
}

2 个答案:

答案 0 :(得分:3)

您不必遍历列。

x <- cor(C,T,method = c("spearman"))

out <- data.frame(MaxCorr = apply(x,1,max), T_ColIndex=apply(x,1,which.max),C_ColIndex=1:nrow(x))

head(out)

给予,

  MaxCorr T_ColIndex C_ColIndex
1       1          8          1
2       1          1          2
3       1          2          3
4       1          1          4
5       1         11          5
6       1          4          6

虚假数据:

C <- matrix(rnorm(3*79),nrow=3)
T <- matrix(rnorm(3*215),nrow=3)

答案 1 :(得分:1)

也许类似下面的函数可以解决问题。

pairwise_cor <- function(x, y, method = "spearman"){
  ix <- seq_len(ncol(x))
  iy <- seq_len(ncol(y))
  t(sapply(ix, function(i){
    m <- sapply(iy, function(j) cor(x[,i], y[,j], method = method))
    setNames(c(i, which.max(m), max(m)), c("col_x", "col_y", "max"))
  }))
}

set.seed(2021)
C <- matrix(rnorm(3*5), nrow=3)
T <- matrix(rnorm(3*7), nrow=3)

pairwise_cor(C, T)
#     col_x col_y max
#[1,]     1     1 1.0
#[2,]     2     2 1.0
#[3,]     3     2 1.0
#[4,]     4     3 0.5
#[5,]     5     5 1.0
相关问题