How to find mean for x number of rows in a column in an R matrix?



To find the mean for x number of rows in a column, we can use colMeans function by accessing the column and providing the number of rows. For example, if we have a matrix called M that contains 20 rows and 5 columns then we can find the mean of column 5 for 5 number of rows can use the command colMeans(matrix(M[,5],nrow=5))

Example

Consider the below data frame −

 Live Demo

M1<-matrix(rpois(40,8),ncol=2)
M1

Output

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

Finding the column means for 5 rows of column 2 in matrix M1 −

Example

colMeans(matrix(M1[,2],nrow=5))

Output

[1] 8.4 8.0 8.6 7.6

Example

 Live Demo

M2<-matrix(rpois(40,2),ncol=2)
M2

Output

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

Finding the column means for 5 rows of column 1 in matrix M2 −

Example

colMeans(matrix(M2[,1],nrow=10))

Output

[1] 2.1 2.0

Example

 Live Demo

M3<-matrix(rnorm(40),ncol=2)
M3

Output

        [,1]         [,2]
[1,]  -0.86899396   0.18289633
[2,]   1.94158458  -0.41550961
[3,]  -0.01652085   0.33423246
[4,]  -0.42176679  -0.13531805
[5,]  -0.12017362   0.06968550
[6,]   0.03800341   0.58490129
[7,]  -1.18465429  -0.82407038
[8,]  -0.73443569  -0.82960221
[9,]  -0.24319549   2.37106377
[10,]  0.78948173  -0.43151208
[11,]  1.57152561  -1.10791821
[12,] -0.77984591   1.13553555
[13,]  0.20805120  -0.83979624
[14,] -0.56464950  -0.15396888
[15,] -0.88983476   0.49162747
[16,] -0.97218350   2.21226831
[17,] -0.10437036  -1.97389026
[18,]  0.38189778  -0.47881007
[19,]  0.61784737   0.07162197
[20,]  0.25541676   0.02707504

Finding the column means for 5 rows of column 1 in matrix M3 −

Example

colMeans(matrix(M3[,1],nrow=10))

Output

[1] -0.08206710 -0.02761453

Advertisements