R Func Mean
# R mean() Function - Calculating the Mean
[ R Language Examples](#)
The R mean() function is used to calculate the mean (average) of a sample. The second parameter of this function can be set to remove some outlier data.
The syntax format of the mean() function is as follows:
mean(x, trim = 0, na.rm = FALSE, ...)
**Parameter Description:**
* **x** Input vector
* **trim** Removes outliers from both ends. The value range is between 0 and 0.5, representing the proportion of outliers to be removed before calculating the mean.
* **na.rm** A logical value, defaulting to FALSE. It specifies whether to remove missing values (NA) from the input vector. Set to TRUE to remove NAs.
## Example
# Create a vector
x <-c(12,27,3,4.2,2,2,54,-21,4,-2)
# Calculate the mean
result.mean<-mean(x)
print(result.mean)
Executing the above code outputs the following result:
8.52
Next, we use the trim parameter to remove some outliers. In the following example, we set trim = 0.3, which will remove **20*0.3=6** data points from the ends of the vector. The leftmost **(1, 2, 3)** and the rightmost **(18, 19, 20)** will be deleted.
## Example
# Create a vector
x <-c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
# Calculate the mean
result.mean<-mean(x,trim =0.3)
result.mean2<-mean(c(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17))
print(result.mean)
print(result.mean2)
In the example above, mean(x,trim = 0.3) removes 3 elements from each end, which is equivalent to mean(c(4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17)).
Executing the above code outputs the following result:
10.5 10.5
If elements in the input vector of the mean function have no value, they default to NA. We can use the third parameter to set whether to remove the default NA values. If NAs are not removed, the result returned is NA:
## Example
# Create a vector
x <-c(1,2,3,4.5,6,NA)
# Calculate the mean
result.mean<-mean(x)
print(result.mean)
# Remove NAs
result.mean<-mean(x,na.rm= TRUE)
print(result.mean)
Executing the above code outputs the following result:
NA 3.3
[ R Language Examples](#)
YouTip