【问题标题】:R function to find the vector with the highest correlation with all the remaining vectorsR函数找到与所有剩余向量具有最高相关性的向量
【发布时间】:2020-05-21 16:32:58
【问题描述】:

我想找出矩阵中哪个向量(或行)与其他向量(行)的相关值最高。除了在这样的循环中执行此操作之外,还有其他解决方案吗:

mat <- matrix(rnorm(100), 5, 5)
for (i in 1:nrow(mat)){
  for (j in 1:nrow(mat)){
    # the correlation coefficients of each row
    cor_val[[i]][[j]] <- cor(mat[i,], mat[j,])
    # the average of the correlation coefficients of each row 
    cor_mean[[i]] <- mean(unlist(cor_val[[i]]))
  }
}

# the index of the row with the highest correlation
Indx <- which.max(cor_mean)

【问题讨论】:

  • cor_mean[[i]] &lt;- ... 行应该放在嵌套循环的第一层。

标签: r correlation


【解决方案1】:

一种方法是使用cor。正如@Darren Tsai 所指出的,cor 按列计算相关性,但您可以使用t 进行转置。

set.seed(3)
mat <- matrix(rnorm(100),5,5)

cor.mat <- cor(t(mat),t(mat))
max.cor <- max(abs(cor.mat[lower.tri(cor.mat)]))
which(abs(cor.mat) == max.cor, arr.ind = TRUE)
#     row col
#[1,]   3   2
#[2,]   2   3

编辑 忘记在which 中调用abs,已修复。

【讨论】:

  • 我在 12 分钟前编辑将 abs 包含在对 which 的调用中。如果还是不行,请告诉我。
  • 哦,这是我的错...我没有刷新我的网络。对了,cor(t(mat),t(mat))可以简化为cor(t(mat))
  • 是的,我经常为提供一个最短的答案而产生矛盾,该答案是 vs 我认为 OP 可能最能理解的答案。这是一个艰难的平衡。
【解决方案2】:

从您的循环代码中,相应的较短版本是

which.max(rowMeans(cor(t(mat))))

但是,相关系数可以是正数或负数。计算平均值将平衡相关强度。我认为最好计算绝对相关平方相关的平均值。即

which.max(rowMeans(abs(cor(t(mat)))))

which.max(rowMeans(cor(t(mat))^2))

【讨论】:

    【解决方案3】:

    您可以只做cor(mat) 来获得相关索引的矩阵。由于Cor() 返回列之间的相关性,因此您必须首先转置矩阵。

    mat <- matrix(rnorm(100),5,4)
    
    mat <- t(mat)
    
    cor(mat)
    

    【讨论】:

    • cor 计算矩阵列之间的相关性。不是行。
    • 那么先转置矩阵呢?
    • *我现在才注意到我的答案没有提供最高相关值的位置,但@Ian Campbell 提供了 - 您可以参考它以获得完整的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-10
    • 2020-06-22
    • 2015-08-26
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多