# How to find the mean of all matrices stored in an R list?

R ProgrammingServer Side ProgrammingProgramming

To find the mean of all matrices stored in an R list, we can use sapply function along with mean function. For example, if we have a list called LIST that contains some matrices then the mean of each matrix can be found by using the command given below −

sapply(LIST,mean)

Check out the below given example to understand how it works.

## Example

Following snippet creates a list of matrices −

M1<-matrix(rpois(40,5),ncol=2)
M2<-matrix(rpois(40,1),ncol=2)
M3<-matrix(rpois(40,10),ncol=2)
List<-list(M1,M2,M3)
List

The following matrices are created −

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

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

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

To find the mean of matrices stored in List, add the following code to the above snippet −

M1<-matrix(rpois(40,5),ncol=2)
M2<-matrix(rpois(40,1),ncol=2)
M3<-matrix(rpois(40,10),ncol=2)
List<-list(M1,M2,M3)
sapply(List,mean)

## Output

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

 4.675 1.025 10.475