How to find the column means for each matrix stored in an R list?


To find the column mean of all matrices stored in an R list, we can use sapply function along with colMeans function.

For example, if we have a list called LIST that contains some matrices then the col means for each matrix can be found by using the command

sapply(LIST,colMeans)

Check out the below example to understand how it works.

Example

Following snippet creates list of matrices −

M1<-matrix(round(rnorm(45),1),ncol=3)
M2<-matrix(round(rnorm(45),1),ncol=3)
M3<-matrix(round(rnorm(45),1),ncol=3)
M4<-matrix(round(rnorm(45),1),ncol=3)
List<-list(M1,M2,M3,M4)
List

Output

The following matrices are created −

[[1]]
      [,1]  [,2]  [,3]
[1,]  -1.6  0.4  -1.5
[2,]   0.1 -0.2  -0.3
[3,]   0.4  0.1   0.4
[4,]   1.2  0.8  -0.1
[5,]  -2.0 -1.0  -0.4
[6,]  -0.5  0.8  -1.2
[7,]   0.2 -1.0  -3.0
[8,]  -0.8  0.1   1.1
[9,]  -2.7 -0.4   1.9
[10,]  0.7 -0.9   0.9
[11,] -0.8 -0.1   0.2
[12,]  0.2 -0.4   0.2
[13,]  0.3 -0.8   0.3
[14,]  0.3 -0.8  -0.2
[15,]  1.1  0.4  -0.2

[[2]]
      [,1]  [,2]   [,3]
[1,]  -0.4   1.2  -1.6
[2,]   0.4  -0.5  -0.2
[3,]  -1.8  -1.2  -0.7
[4,]  -1.3  -1.7   1.4
[5,]   0.9   0.2  -0.3
[6,]   0.2   0.7   1.1
[7,]   0.6   0.6   0.4
[8,]   0.2   0.2  -0.2
[9,]  -1.0   0.8  -0.7
[10,] -1.0   0.1  -0.1
[11,] -0.7   1.5  -0.2
[12,] -1.3  -0.3   2.2
[13,]  0.9   0.3   0.7
[14,] -0.4   0.7   0.0
[15,] -1.0   1.2   0.6

[[3]]
      [,1]  [,2]  [,3]
[1,]   2.2  -0.1   0.0
[2,]  -1.6   0.4  -0.9
[3,]  -1.5  -1.0   1.3
[4,]  -0.4  -0.2   1.6
[5,]  -0.8  -0.7   0.3
[6,]  -1.2  -0.1  -0.9
[7,]   0.9   0.9  -1.3
[8,]   1.1   0.9  -0.4
[9,]  -0.4  -0.4   0.4
[10,]  1.1  -0.6   0.5
[11,]  0.4   0.8  -0.9
[12,] -0.8  -1.7   0.8
[13,] -1.5  -0.2   0.1
[14,]  0.5  -0.7  -0.7
[15,] -0.7  -0.7   0.6

[[4]]
      [,1]  [,2]  [,3]
[1,]   0.5  -0.8  -1.5
[2,]   0.1   0.3   0.0
[3,]  -1.5   0.2   0.5
[4,]   0.8  -1.5   0.2
[5,]   1.0  -1.3   0.5
[6,]   0.0  -1.4   1.2
[7,]   0.0  -1.9  -0.7
[8,]   0.7  -0.5   0.1
[9,]  -0.4  -0.1   0.5
[10,] -0.3  -0.6   0.6
[11,]  3.1   0.2   0.3
[12,]  0.9   0.4  -0.4
[13,] -0.1  -1.2  -0.6
[14,]  1.5  -1.1   0.8
[15,] -1.5  -0.2  -1.2

To find column means for each matrix in List, add the following code to the above snippet −

M1<-matrix(round(rnorm(45),1),ncol=3)
M2<-matrix(round(rnorm(45),1),ncol=3)
M3<-matrix(round(rnorm(45),1),ncol=3)
M4<-matrix(round(rnorm(45),1),ncol=3)
List<-list(M1,M2,M3,M4)
sapply(List,colMeans)

Output

If you execute all the above given snippets as a single program, it generates the following Output −

         [,1]       [,2]        [,3]        [,4]
[1,] -0.2600000  -0.3800000  -0.18000000  0.3200000
[2,] -0.2000000   0.2533333  -0.22666667 -0.6333333
[3,] -0.1266667   0.1600000   0.03333333  0.0200000

Updated on: 03-Nov-2021

392 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements