What is mean() Function in R (4 Examples)

The mean() is a built-in R function that takes an input vector as an argument and returns the mean of the vector elements. For example, mean(c(1, 2, 3)) function returns 2.

Syntax

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

Parameters

The x is an input vector.

The trim drops some observations from both ends of the sorted vector.

The na.rm is used to remove the missing values from the input vector.

Example 1: How to find a mean of a vector in R

The mean is calculated by taking a sum of the values and dividing it by the number of values in the data. If the data series is a vector, the mean is calculated by taking a sum of vector elements and dividing it by the number of elements of the series.

``````# Create a vector.
rv <- c(11, 18, 19, 21, 29, 46)

# Find Mean of rv vector.
meanResult <- mean(rv)
print(meanResult)``````

Output

``````[1] 24
``````

That means the sum of all the vector elements is 144, and 144 / 6 is 24.

Example 2: Passing the trim option to the mean() function

The mean() function optionally takes the trim parameter. When you pass the trim parameters, the values in the vector get sorted, and then the required observations are dropped from calculating the mean.

If you pass the 0.3, 3 values from each end will be dropped from the calculations to find the mean.

``````# Create a vector.
rv <- c(11, 18, 19, 21, 29, 46)

# Find Mean of rv vector.
meanResult <- mean(rv, trim = 0.3)
print(meanResult)``````

Output

``[1] 21.75``

Example 3: Passing NA Option

If there are missing values, then the mean() function returns NA.

``````# Create a vector.
rv <- c(11, 18, 19, NA, 29, 46)

# Find Mean of rv vector.
meanResult <- mean(rv)
print(meanResult)``````

Output

``[1] NA``

To drop the missing values from the calculation, use na.rm = TRUE. Which means removing the NA values.

``````# Create a vector.
rv <- c(11, 18, 19, NA, 29, 46)

# Find Mean of rv vector.
meanResult <- mean(rv, na.rm = TRUE)
print(meanResult)``````

Output

``[1] 24.6``

Example 4: How to apply the mean() function on a data frame

To apply the mean() function to a dataframe in R, you can use the apply() function. The apply() function takes a dataframe or a matrix as an input and applies a function to each row or column. For example, if you have a dataframe called df with four columns, A, B, C, and D, you can calculate the mean of each column by using apply(df, 2, mean). This will return a vector of four means.

``````# Create a sample data frame
df <- data.frame(x = c(1, 2, 3), y = c(4, 5, 6), z = c(7, 8, 9))

# Apply mean() function to each column
means <- apply(df, 2, mean)

# Print the means
print(means)``````

Output

``````x   y   z
2   5   8``````

Conclusion

In R, you can calculate the mean of a vector using the mean() function. The function accepts a vector as input and returns the average as a numeric.