Mean in R: How to Find Mean of Vectors in R

Statistical functions take the R vector as an input besides the arguments and give the result. R has many inbuilt statistical functions, and mean() is one of them. The mean of an observation variable is a numerical measure of the prime location of the data values. Mean is the sum of its data values divided by data count.

Mean in R

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

To calculate the mean in R, use an inbuilt mean() function.

Syntax

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

Parameters

The x is an input vector.

The trim is used to drop some observations from both ends of the sorted vector.

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

Example

# 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.

Passing trim option

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 numbers of 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

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 remove 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

Conclusion

R mean() is an inbuilt function that calculates the arithmetic mean. The mean() function takes optional parameters that you can use according to your needs.

See also

Sum in R

R append to list

R array

R factor

R list

Leave a Comment