How to find the correlation between corresponding columns of two matrices in R?

To find the correlation between corresponding columns of two matrices, we can use mapply function but we will have to read the matrices using as.data.frame function. For example, if we have two matrices called M_1 and M_2 and each of these matrices contains 5 columns then the correlation between corresponding columns of these matrices can be found by using the command mapply(cor,as.data.frame(M_1),as.data.frame(M_2))

Example

Consider the below matrices −

M1<-matrix(1:40,ncol=2)
M1

Output

    [,1] [,2]
[1,]  1   21
[2,]  2   22
[3,]  3   23
[4,]  4   24
[5,]  5   25
[6,]  6   26
[7,]  7   27
[8,]  8   28
[9,]  9   29
[10,] 10  30
[11,] 11  31
[12,] 12  32
[13,] 13  33
[14,] 14  34
[15,] 15  35
[16,] 16  36
[17,] 17  37
[18,] 18  38
[19,] 19  39
[20,] 20  40

Example

M2<-matrix(1:40,ncol=2)
M2

Output

    [,1] [,2]
[1,]  1   21
[2,]  2   22
[3,]  3   23
[4,]  4   24
[5,]  5   25
[6,]  6   26
[7,]  7   27
[8,]  8   28
[9,]  9   29
[10,] 10  30
[11,] 11  31
[12,] 12  32
[13,] 13  33
[14,] 14  34
[15,] 15  35
[16,] 16  36
[17,] 17  37
[18,] 18  38
[19,] 19  39
[20,] 20  40

Finding the correlation between column 1 of M1 and column 1 of M2 for both the columns −

Example

mapply(cor,as.data.frame(M1),as.data.frame(M2))

Output

V1 V2
1 1

Example

M3<-matrix(rpois(40,5),ncol=2)
M3

Output

    [,1] [,2]
[1,]  3    6
[2,]  4    6
[3,]  9    3
[4,]  1    7
[5,]  6    5
[6,]  4    2
[7,]  1    3
[8,]  1    3 
[9,]  5    2
[10,] 4    1
[11,] 3    5
[12,] 6    8
[13,] 3    4
[14,] 6    6
[15,] 3    5
[16,] 3    6
[17,] 4    5
[18,] 4    5
[19,] 5    4
[20,] 3    7

Example

M4<-matrix(rpois(40,5),ncol=2)
M4

Output

     [,1] [,2]
[1,]  3   4
[2,]  7   5
[3,]  6   5
[4,]  8   4
[5,]  7   5
[6,]  6   4
[7,]  8   0
[8,]  3   5
[9,]  2   7
[10,] 6   6
[11,] 4   4
[12,] 6   5
[13,] 8   4
[14,] 5   8
[15,] 4   2
[16,] 7   2
[17,] 6   4
[18,] 3   2
[19,] 4   5
[20,] 4   7

Finding the correlation between column 1 of M3 and column 1 of M4 for both the columns −

Example

mapply(cor,as.data.frame(M3),as.data.frame(M4))

Output

V1 V2
-0.06220599 0.01182284
Updated on: 2026-03-11T22:50:56+05:30

933 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements