【问题标题】:Correlation between two matrices of different dimensions两个不同维度的矩阵之间的相关性
【发布时间】:2021-05-18 09:28:07
【问题描述】:

我对 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"))))
  }
}

【问题讨论】:

  • 嗨,所以基本上你是在 3vs3 向量上做 spearman 对吧?因为观察次数和斯皮尔曼相关系数如此之低,你很容易有1个相关性,只有3个值,这有点冒险不是吗?
  • 只有3个值,你只能得到:0.5; -0.5; 1;-1 使用 spearman 相关性。皮尔逊不是更适应吗?
  • 你说得对,Pearson 对我来说要好得多。但这里更重要的是拥有正确的代码,无论是使用 Spearman 还是 Pearson。谢谢你的回答。

标签: r correlation


【解决方案1】:

您不必遍历列。

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)

【讨论】:

    【解决方案2】:

    也许像下面的函数可以解决这个问题。

    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
    

    【讨论】:

      猜你喜欢
      • 2013-08-17
      • 2012-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多