Row-wise correlations in R

六眼飞鱼酱① 提交于 2019-12-02 00:46:39

This should be fast:

cA <- A - rowMeans(A)
cB <- B - rowMeans(B)
sA <- sqrt(rowMeans(cA^2))
sB <- sqrt(rowMeans(cB^2))

rowMeans(cA * cB) / (sA * sB)

You could create vectorized functions that will calculate covariance and SD for you such as,

RowSD <- function(x) {
  sqrt(rowSums((x - rowMeans(x))^2)/(dim(x)[2] - 1))
}

VecCov <- function(x, y){
  rowSums((x - rowMeans(x))*(y - rowMeans(y)))/(dim(x)[2] - 1)
}

Then, simply do

VecCov(A, B)/(RowSD(A) * RowSD(B))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!