R Mean, Median & Mode
The mean, median and mode all describe a "typical" value, but in different ways. Choosing the right one depends on your data.
| Measure | Definition | R |
|---|---|---|
| Mean | sum of the values divided by their count | mean(x) |
| Median | the middle value of the sorted data | median(x) |
| Mode | the most frequent value | no built-in, see below |
Mean
wt <- mtcars$wt
mean(wt)
sum(wt) / length(wt) # the same thing, by hand[1] 3.21725
[1] 3.21725
mean() has a trim argument that drops a fraction of the smallest and largest values before averaging, which makes it less sensitive to outliers:
salaries <- c(32, 35, 38, 40, 41, 43, 45, 250) # in thousands
mean(salaries)
mean(salaries, trim = 0.125) # drop 1 value from each end
median(salaries)[1] 65.5
[1] 40.33333
[1] 40.5
One very high salary drags the mean far above what most people earn; the median and trimmed mean stay close to the typical value.
Median
To find the median, R sorts the values and takes the middle one. With an even number of values it averages the two middle ones:
median(c(7, 1, 5)) # sorted: 1 5 7
median(c(7, 1, 5, 3)) # sorted: 1 3 5 7, so (3 + 5) / 2
median(mtcars$hp)[1] 5
[1] 4
[1] 123
Mode
R has a function called mode(), but it returns the storage mode of an object (such as "numeric"), not the statistical mode! Find the most frequent value with table():
mode(mtcars$cyl) # not what we want
counts <- table(mtcars$cyl)
counts
names(counts)[which.max(counts)][1] "numeric"
4 6 8
11 7 14
[1] "8"
A small helper makes this reusable and handles ties by returning every most-frequent value:
stat_mode <- function(x) {
counts <- table(x)
names(counts)[counts == max(counts)]
}
stat_mode(mtcars$gear)
stat_mode(c("red", "blue", "red", "blue", "green"))[1] "3"
[1] "blue" "red"
Missing values and groups
All of these functions return NA when the data contains NA, unless you pass na.rm = TRUE. Combine them with tapply() or aggregate() to compute them per group:
mean(airquality$Ozone, na.rm = TRUE)
median(airquality$Ozone, na.rm = TRUE)
aggregate(weight ~ group, data = PlantGrowth, FUN = mean)[1] 42.12931
[1] 31.5
group weight
1 ctrl 5.032
2 trt1 4.661
3 trt2 5.526
Which one should I use?
- Mean: symmetric data without extreme values (heights, test scores). It uses every value.
- Median: skewed data or data with outliers (incomes, house prices, waiting times).
- Mode: categorical data (most common colour, most popular product), or discrete counts.
The Ozone values above illustrate the difference: the mean is clearly larger than the median because a few very polluted days pull it up.
Test yourself
What is median(c(10, 2, 8, 4))?
- 6
- 8
- 4
- 5
What does mode(c(1, 2, 2)) return in R?
- 2
- "numeric"
- 1
- An error
For heavily skewed data like incomes, which measure of center is usually best?
- Mean
- Median
- Maximum
- Sum