繁体   English   中英

R function 找到与所有剩余向量相关性最高的向量

[英]R function to find the vector with the highest correlation with all the remaining vectors

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

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)

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

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

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

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

或者

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

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

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

mat <- t(mat)

cor(mat)

一种方法是使用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

编辑忘记了对abs which的调用,已修复。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM