mean()
mean(x, trim = 0, na.rm = FALSE, ...) Returns:
numeric · Updated March 13, 2026 · Base Functions statistics mean base
The mean() function calculates the arithmetic average of all values in a numeric vector. It is one of the most commonly used statistical functions in R, providing a simple measure of central tendency.
Syntax
mean(x, trim = 0, na.rm = FALSE, ...)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
x | numeric vector | required | A numeric vector containing the values to average |
trim | numeric | 0 | Fraction of observations to trim from each end before computing the mean (0 to 0.5) |
na.rm | logical | FALSE | If TRUE, remove NA values before computing |
... | additional arguments | none | Passed to or from other methods |
Examples
Basic usage
# Simple mean of a vector
values <- c(10, 20, 30, 40, 50)
mean(values)
# [1] 25
Handling NA values
# Vector with NA values
data_with_na <- c(1, 2, NA, 4, 5)
# Without na.rm - returns NA
mean(data_with_na)
# [1] NA
# With na.rm = TRUE - ignores NA
mean(data_with_na, na.rm = TRUE)
# [1] 3.5
Using trim for robust statistics
# Vector with outliers
outlier_data <- c(1, 2, 3, 4, 5, 100)
# Regular mean - affected by outlier
mean(outlier_data)
# [1] 19.16667
# Trimmed mean - removes 10% from each end
mean(outlier_data, trim = 0.1)
# [1] 3.5
Mean of matrix columns
# Calculate mean of each column in a matrix
mat <- matrix(1:12, nrow = 3, ncol = 4)
colMeans(mat)
# [1] 5 6 7 8
Common Patterns
Weighted mean
# Use weighted.mean() for weighted calculations
weights <- c(0.1, 0.2, 0.3, 0.2, 0.2)
values <- c(10, 20, 30, 40, 50)
weighted.mean(values, weights)
# [1] 3.51
Mean by group using tapply
# Calculate mean by group
group <- c("A", "A", "B", "B", "A", "B")
value <- c(10, 15, 20, 25, 12, 22)
tapply(value, group, mean)
# A B
# 12.3 22.3
Running mean (rolling average)
# Calculate rolling mean
x <- 1:10
library(zoo)
rollmean(x, 3, align = "center")
# [1] 2 3 4 5 6 7 8 9