R mean Function


mean() function calculates the arithmetic mean.

mean(x, trim = 0, na.rm = FALSE, ...)


x: numeric vector
trim: trim off a fraction at each end of the vector, default is 5%
na.rm: whether NA should be removed, if not, NA will be returned
...

>x <- c(1,2.3,2,3,4,8,12,43,-4,-1)
>mean(x)

[1] 7.03


Missing value affect the results:

>y<- c(x,NA)
>y

[1] 1.0 2.3 2.0 3.0 4.0 8.0 12.0 43.0 -4.0 -1.0 NA

>mean(y)

[1] NA


After define na.rm=TRUE, result is meaningful:

>mean(y,na.rm=TRUE)

[1] 43


Trim at each end:

>z <- c(rep(1:20),-200,400)
>mean(z)

[1] 18.63636

>mean(z,trim=0.5)

[1] 10.5

colMeans() and rowMeans() functions calculate the column and row means of a matrix.

> 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
> rowMeans(x)
[1] 4 5 6


You may check aggregate() function for calculating the mean of each group of a data frame.

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