如何计算两个矩阵的相应列之间的相关性,而不是将其他相关性作为输出

rde*_*der 7 r correlation

我有这些数据

> a
     a    b    c
1    1   -1    4
2    2   -2    6
3    3   -3    9
4    4   -4   12
5    5   -5    6

> b
     d    e    f
1    6   -5    7
2    7   -4    4
3    8   -3    3
4    9   -2    3
5   10   -1    9

> cor(a,b)
           d            e             f
a  1.0000000    1.0000000     0.1767767
b -1.0000000    -1.000000    -0.1767767
c  0.5050763    0.5050763    -0.6964286
Run Code Online (Sandbox Code Playgroud)

我想要的结果就是:

cor(a,d) = 1
cor(b,e) = -1
cor(c,e) = 0.6964286
Run Code Online (Sandbox Code Playgroud)

小智 9

上面的第一个答案计算所有成对相关性,除非矩阵很大,否则第二个不成功.据我所知,必须直接进行有效的计算,例如借用于arrayMagic Bioconductor包中的这些代码,可以有效地用于大型矩阵:

> colCors = function(x, y) { 
+   sqr = function(x) x*x
+   if(!is.matrix(x)||!is.matrix(y)||any(dim(x)!=dim(y)))
+     stop("Please supply two matrices of equal size.")
+   x   = sweep(x, 2, colMeans(x))
+   y   = sweep(y, 2, colMeans(y))
+   cor = colSums(x*y) /  sqrt(colSums(sqr(x))*colSums(sqr(y)))
+   return(cor)
+ }

> set.seed(1)
> a=matrix(rnorm(15),nrow=5)
> b=matrix(rnorm(15),nrow=5)
> diag(cor(a,b))
[1]  0.2491625 -0.5313192  0.5594564
> mapply(cor,a,b)
 [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
> colCors(a,b)
[1]  0.2491625 -0.5313192  0.5594564
Run Code Online (Sandbox Code Playgroud)


Jos*_*ich 4

我个人可能会使用diag

> diag(cor(a,b))
[1]  1.0000000 -1.0000000 -0.6964286
Run Code Online (Sandbox Code Playgroud)

但你也可以使用mapply

> mapply(cor,a,b)
         a          b          c 
 1.0000000 -1.0000000 -0.6964286
Run Code Online (Sandbox Code Playgroud)