R中的行相关 [英] Row-wise correlations in R
本文介绍了R中的行相关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个大小相同的矩阵。我想计算这些矩阵中每对行之间的相关系数; A的第1行与B的第1行,A的第2行与B的第2行,等等。
I have two matrices of the same size. I would like to calculate the correlation coefficient between each pair of rows in these matrices; row 1 from A with row 1 B, row 2 from A with row 2 from B etc.
A <- matrix(runif(1:200), nrow=20)
B <- matrix(runif(1:200), nrow=20)
我能想出的最好的方法是
Best I could come up with is
ret <- sapply(1:20, function(i) cor(A[i,], B[i,]))
但效率极低(矩阵有成千上万的行)。有没有更好,更快的方法?
but it is terribly inefficient (the matrices have tens of thousands of rows). Is there a better, faster way?
推荐答案
这应该很快:
cA <- A - rowMeans(A)
cB <- B - rowMeans(B)
sA <- sqrt(rowMeans(cA^2))
sB <- sqrt(rowMeans(cB^2))
rowMeans(cA * cB) / (sA * sB)
这篇关于R中的行相关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文