rguides

mean()

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

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

ParameterTypeDefaultDescription
xnumeric vectorrequiredA numeric vector containing the values to average
trimnumeric0Fraction of observations to trim from each end before computing the mean (0 to 0.5)
na.rmlogicalFALSEIf TRUE, remove NA values before computing
...additional argumentsnonePassed to or from other methods

Examples

Basic usage

# Simple mean of a vector
values <- c(10, 20, 30, 40, 50)
mean(values)
# [1] 25

Real-world data rarely arrives clean — missing values are the norm, not the exception. In R, NA values propagate through arithmetic operations, so a single missing element causes mean() to return NA by default. The na.rm parameter gives you explicit control over whether to strip those missing values before the calculation runs.

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

Once missing values are handled, the next concern is outliers — extreme observations that can pull the arithmetic mean far from the center of the bulk of the data. R’s trim argument addresses this by discarding a fraction of the smallest and largest values before averaging, giving you a measure of central tendency that resists the influence of a few extreme points.

Using trim for reliable 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

When your data lives in a matrix rather than a flat vector, applying mean() to the whole matrix computes a single grand average across all elements — which is rarely what you want. For column-wise or row-wise summaries, R provides the specialized colMeans() and rowMeans() functions that operate along a specific margin and are considerably faster than looping with apply().

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

The examples so far treat every observation equally, but many analyses call for unequal contributions — survey responses with sampling weights, portfolio returns weighted by investment size, or grades weighted by credit hours. R’s weighted.mean() extends the simple average to handle these cases, accepting a parallel vector of weights alongside the data values.

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

Weighted averages handle observation-level importance, but a different kind of structure appears when your data splits naturally into categories — treatment vs. control, regions, or time periods. Base R’s tapply() applies mean() to each subset defined by a grouping factor, returning a named vector of per-group averages in a single call without any external package dependencies.

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

Grouped averages summarize static categories, but time-series and sequential data need a different tool: the rolling mean smooths out short-term fluctuations by averaging a sliding window of consecutive observations. The zoo package provides rollmean(), which accepts a window width and alignment parameter, making it straightforward to compute moving averages for trend detection.

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

mean() in practice

mean() computes the arithmetic mean. For numeric vectors with no missing values, it is equivalent to sum(x) / length(x). With na.rm = TRUE, it removes NA values before computing: mean(c(1, 2, NA), na.rm = TRUE) returns 1.5. Without na.rm, any NA in the input produces NA output.

For weighted means, use weighted.mean(x, w) where w is a vector of weights. The weights do not need to sum to 1. For trimmed means (less sensitive to outliers), use mean(x, trim = 0.1) which trims the top and bottom 10% of observations before averaging.

mean() on integer vectors returns a double, even though the inputs are integers. This is intentional, the average of integers is generally not an integer. mean(c(1L, 3L)) returns 2.0, not 2L. If you need an integer result, wrap with as.integer().

For grouped means in data analysis, tapply(x, groups, mean) and dplyr::summarise(df, m = mean(col)) are the standard approaches. The dplyr approach integrates with group_by() and handles multiple summary statistics at once. colMeans() and rowMeans() compute means across matrix columns and rows respectively, and are faster than applying mean() with apply() for matrix inputs.

mean() computes the arithmetic mean and is NA-propagating by default. Set na.rm = TRUE to exclude missing values. The trim argument removes a fraction of observations from each end before computing the mean, mean(x, trim = 0.1) computes a 10% trimmed mean, which is more reliable to outliers than the full mean.

For weighted means, use weighted.mean(x, w). For geometric and harmonic means, which are appropriate for ratios and rates, use exp(mean(log(x))) and 1/mean(1/x) respectively, base R does not have dedicated functions for these.

mean() on a logical vector gives the proportion of TRUE values: mean(x > 0) is the fraction of positive elements. This is more concise than sum(x > 0) / length(x).

For integer arithmetic, mean() returns a double even if the result is whole-numbered. When applied to a matrix or data frame, mean() computes the grand mean of all values, not column means — use colMeans() for column-wise averages.

See also