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

(meanx, 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

1 2 3 | x = c(1,2,3,4,5,6,7,8,9,45) xm = mean(x) c(xm) |

1 | [1] 5 |

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

1 2 3 | x = c(1,2,3,4,5,6,7,8,9,45) xm = mean(x, trim=0.10) c(xm) |

1 | [1] 5.5 |

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

1 2 3 | x = c(1,2,3,4,5,6,7,8,9,45,NA) xm = mean(x, trim=0.0, na.rm=TRUE) c(xm) |

1 | [1] 9 |

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

1 2 3 | x = c(1,2,3,4,5,6,7,8,9,45,NA) xm = mean(x, trim=0.0, na.rm=TRUE) c(xm) |

1 | [1] NA |

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

1 2 3 | x = c(TRUE, FALSE, FALSE, FALSE, TRUE) xm = mean(x) c(xm) |

1 | [1] 0.4 |

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.