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

R ProgrammingServer Side ProgrammingProgramming

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

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

sapply(LIST,rowMeans)

Check out the below example to understand how it works.

Example

Following snippet creates the matrices −

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

output

The following matrices are created −

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

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

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

Now, in order to find the row means for each matrix in List, add the following code to the above snippet −

Example

sapply(List,rowMeans)

Output

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

      [,1] [,2]  [,3]
[1,]  2.0  3.5   6.0
[2,]  2.0  1.0   5.5
[3,]  1.5  1.0  10.0
[4,]  1.5  2.0   2.5
[5,]  3.5  2.5   3.5
[6,]  2.5  1.0   5.5
[7,]  2.5  1.5   6.5
[8,]  2.5  0.5   4.0
[9,]  0.5  2.0   2.5
[10,] 2.0  1.0   6.5
[11,] 3.0  2.5   6.0
[12,] 1.0  3.0   4.0
[13,] 0.5  2.5   3.5
[14,] 1.5  5.0   2.5
[15,] 2.0  2.5   7.0
[16,] 3.5  3.5   7.0
[17,] 1.5  3.0   4.5
[18,] 0.5  2.0   5.0
[19,] 3.0  2.0   6.5
[20,] 3.0  2.0   7.5
raja
Updated on 02-Nov-2021 06:23:25

Advertisements