Row-wise correlations in R

后端 未结 2 1661
孤街浪徒
孤街浪徒 2021-01-22 16:12

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

相关标签:
2条回答
  • 2021-01-22 16:50

    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))
    
    0 讨论(0)
  • 2021-01-22 16:54

    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)
    
    0 讨论(0)
提交回复
热议问题