Home » How to Use mean Function in R (With Examples)

How to Use mean Function in R (With Examples)

by Erma Khan

You can use the mean() function in R to calculate the mean of values in a vector:

mean(x)

The following examples show how to use this function in practice.

Example 1: Calculate Mean of Vector

The following code shows how to calculate the mean value of a vector in R:

#define vector
x #calculate mean of vector
mean(x)

[1] 12.66667

If your vector has missing values, be sure to specify na.rm = TRUE to ignore missing values when calculating the mean:

#define vector with some missing values
x #calculate mean of vector
mean(x, na.rm = TRUE)

[1] 11.85714

You can also use the trim argument to trim a certain fraction (0 to 0.5) of observations from each end of a vector before calculating the mean:

#define vector
x #calculate mean of vector after trimming 20% of observations off each end
mean(x, trim = 0.2)

[1] 12.42857

Example 2: Calculate Mean of Column in Data Frame

The following code shows how to calculate the mean value of a certain column in a data frame:

#define data frame
df frame(a=c(3, 6, 7, 7, 12, 14, 19, 22, 24),
                 b=c(4, 4, 5, 12, 13, 14, 9, 1, 2),
                 c=c(5, 6, 6, 3, 5, 5, 6, 19, 25))

#calculate mean of column 'a'
mean(df$a)

[1] 12.66667

Example 3: Calculate Mean of Several Columns in Data Frame

The following code shows how to use the apply() function to calculate the mean of several columns in a data frame:

#define data frame
df frame(a=c(3, 6, 7, 7, 12, 14, 19, 22, 24),
                 b=c(4, 4, 5, 12, 13, 14, 9, 1, 2),
                 c=c(5, 6, 6, 3, 5, 5, 6, 19, 25))

#calculate mean of columns 'a' and 'c'
apply(df[ , c('a', 'c')], 2, mean)

        a         c 
12.666667  8.888889

Additional Resources

How to Calculate the Mean by Group in R
How to Calculate a Weighted Mean in R
How to Calculate Geometric Mean in R

Related Posts