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 a built-in R function that takes an input vector as an argument and returns the mean of the vector elements. 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, 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.
mean(x, trim = 0, na.rm = FALSE, ...)
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.
# Create a vector. rv <- c(11, 18, 19, 21, 29, 46) # Find Mean of rv vector. meanResult <- mean(rv) print(meanResult)
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)
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)
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)
R mean() is a built-in function that calculates the arithmetic mean. The mean() function takes optional parameters that you can use according to your needs. That’s it for this tutorial.
Krunal Lathiya is an Information Technology Engineer by education and web developer by profession. He has worked with many back-end platforms, including Node.js, PHP, and Python. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language. Krunal has written many programming blogs, which showcases his vast expertise in this field.