Reputation: 21
I have two matrices (different rows and same columns). I want to calculate the corelation between the rows of two matrices. (element-wise corelation).the first one is like this:
A 2 5 B 6 9 c 7 8
and the second one is like this:
D 8 6 E 1 7 F 7 9
in this case the results would be a 3 by 3 matrix (element by element corelation and if possible significance level). how can I make it?
Upvotes: 2
Views: 8534
Reputation: 93761
Is this what you're looking for:
# Create some fake data
set.seed(5) # for reproducibility
mat1 = matrix(rnorm(20), nrow=4)
mat2 = matrix(rnorm(25), nrow=5)
cor(t(mat1),t(mat2)) # With compliments to @user20650
The output is a matrix of correlation coefficients, where the rows of the output matrix are the row indices of mat1
and the columns are the row indices of mat2
.
[,1] [,2] [,3] [,4] [,5]
[1,] -0.8160882 0.6347404 0.4746797 -0.1497491 -0.4571110
[2,] -0.3021956 0.5039831 0.3204012 -0.2516131 0.6280471
[3,] -0.1188116 0.1798996 0.4537378 0.6036471 0.3732481
[4,] 0.6682962 -0.4815078 -0.5085583 -0.1232551 -0.1088882
You can get significance level with rcorr
from the Hmisc
package. rcorr
concatenates the two matrices and returns correlations and significance levels between all pairs of columns. Here's a way to get just the significance levels of correlations between each matrix rather than within each matrix (though there may be an easier way).
The transpose function is just to get the rows and columns to correspond between the correlation matrix above and significance matrix returned below. Also note that you can get the correlation matrix from the code below simply by changing [[3]]
to [[1]]
. rcorr
returns a list with the correlation matrix in the first element and the significance matrix in the third element.
library(Hmisc)
t(sapply(1:nrow(mat1), function(x) {
sapply(1:nrow(mat2), function(y) {
rcorr(mat1[x,],mat2[y,])[[3]][1,2]
})
}))
[,1] [,2] [,3] [,4] [,5]
[1,] 0.09202147 0.2499648 0.4191522 0.8100486 0.4389450
[2,] 0.62117186 0.3866162 0.5991440 0.6830495 0.2565734
[3,] 0.84908109 0.7721863 0.4427686 0.2810484 0.5360431
[4,] 0.21755702 0.4115164 0.3815924 0.8434650 0.8616337
Upvotes: 6