## Calculate mean of a vector in R

In this tutorial, we shall learn to calculate mean of a vector in R

## Mean of a vector

Mean of a vector is the average or arithmetic mean of elements in the vector. A built-in function called mean() is used to calculate mean of a vector in R programming language.

### Syntax of mean() in R

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

where

• x could be numeric vector / logical vector / data object / date-time object / time interval. Also x could be complex vector provided time=0.
• trim range is [0, 0.5]. It is the fraction of elements that would be dropped before calculating mean. trim=0.2 means 20% of elements at the beginning and 20% of the elements at the ending of the vector are removed, and the mean is calculated for the 60% of elements remaining.
• na.rm mean NA REmoval. It could be TRUE or FALSE. If TRUE, NA values in vector would be stripped out before mean computation proceeds.

## Examples to Calculate mean of a vector in R

We shall learn to calculate mean with different options available with mean() function.

### Simple Example with mean() function applied on numeric vector

 xm = (1+2+3+4+5+6+7+8+9+45)/9 = 90/10 = 9

### Example with trim attribute in mean() function applied on numeric vector

trim=0.10 i.e., 10% of elements at starting and ending are removed. 1 and 45 are removed and the mean is calculated with rest of elements in the vector.

 xm = (2+3+4+5+6+7+8+9)/9 = 44/8 = 5.5

### Example with na.rm=TRUE in mean() function applied on numeric vector

na.rm = TRUE removes all the NA values present in vector before calculation proceeds.

 xm = (2+3+4+5+6+7+8+9+45)/9 = 44/8 = 5.5

### Example with na.rm=FALSE in mean() function applied on numeric vector

na.rm = FALSE does not remove NA values present in vector before calculation proceeds. And if NA is present in the vector, mean would be NA irrespective of anything else.

 xm = (1+2+3+4+5+6+7+8+9+45+NA)/9 = NA

If NA s are expected in a vector, na.rm has to be considered.

### Simple Example with mean() function applied on logical vector

For a logical vector, TRUE is considered as 1 and FALSE is considered as 0.

 xm = (TRUE + FALSE + FALSE + FALSE + TRUE)/5 =(1+0+0+0+1)/5 = 2/5 = 0.4

### Conclusion :

In this R Tutorial, we have learnt about mean() function and how to Calculate Mean of a Vector in R with Example R Scripts.