R colMeans Function


colMeans() function computes the means of each column of a matrix or array.

colMeans(x, na.rm = FALSE, dims = 1)


x: array of two or more dimensions, containing numeric, complex, integer or logical values, or a numeric data frame
dims: integer: Which dimensions are regarded as ‘columns’ to sum over. It is over dimensions 1:dims.

> x <- matrix(rep(1:9),3,3)
> x

[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9


> colMeans(x)

[1] 2 5 8


Let's try a three dimensional array.

> x <- array(1:12,c(2,3,3))
> x
, , 1
[,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
, , 2
[,1] [,2] [,3]
[1,]    7    9   11
[2,]    8   10   12
, , 3
[,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
> colMeans(x,dims=1)
#for dims=1, x[,1,1], x[,2,1],x[,3,1], x[,1,2] ... are columns
     [,1] [,2] [,3]
[1,]  1.5  7.5  1.5
[2,]  3.5  9.5  3.5
[3,]  5.5 11.5  5.5
> colMeans(x,dims=2)
#for dims=2, x[,,1], x[,,2],x[,,3] are columns
[1] 3.5 9.5 3.5


endmemo.com © 2024  | Terms of Use | Privacy | Home