R Max and Min
The largest and smallest values are the simplest statistics, but they often answer real questions: what was the hottest day? which car is the most powerful? R gives you the values themselves and the positions where they occur.
max(mtcars$hp)
min(mtcars$hp)
range(mtcars$hp)[1] 335
[1] 52
[1] 52 335
range() returns both at once as a vector c(min, max).
Which observation?
which.max() and which.min() return the position of the (first) maximum or minimum. Use it to look up the matching row:
i <- which.max(mtcars$hp)
i
rownames(mtcars)[i]
rownames(mtcars)[which.min(mtcars$mpg)]
mtcars[which.max(mtcars$mpg), c("mpg", "cyl", "wt")][1] 31
[1] "Maserati Bora"
[1] "Cadillac Fleetwood"
mpg cyl wt
Toyota Corolla 33.9 4 1.835
If several values tie for the maximum, which.max() returns only the first. Use which(x == max(x)) to get all of them:
which(mtcars$cyl == max(mtcars$cyl))[1:5]
sum(mtcars$cyl == max(mtcars$cyl))[1] 5 7 12 13 14
[1] 14
Several vectors at once
max() and min() look at all of their arguments together. pmax() and pmin() ("parallel") compare element by element instead:
a <- c(3, 9, 4)
b <- c(7, 2, 8)
max(a, b)
pmax(a, b)
pmin(a, b)
pmax(c(-2, 5, -1), 0) # clamp negatives to zero[1] 9
[1] 7 9 8
[1] 3 2 4
[1] 0 5 0
Missing values
If a vector contains NA, the answer is NA too: the unknown value might be the largest. Add na.rm = TRUE to ignore missing values:
max(airquality$Ozone)
max(airquality$Ozone, na.rm = TRUE)
range(airquality$Solar.R, na.rm = TRUE)[1] NA
[1] 168
[1] 7 334
Max and min by group
tapply() applies a function to each group of a vector:
tapply(airquality$Temp, airquality$Month, max)
tapply(mtcars$hp, mtcars$cyl, min) 5 6 7 8 9
81 93 92 97 93
4 6 8
52 105 150
Strings and dates
max() and min() also work on characters (alphabetical order) and dates:
max(c("pear", "apple", "zucchini", "fig"))
min(as.Date(c("2024-03-15", "2023-11-02", "2024-01-20")))[1] "zucchini"
[1] "2023-11-02"
Test yourself
What does which.max(c(4, 9, 2, 9)) return?
- 9
- 2
- c(2, 4)
- 4
What is max(c(5, NA, 8))?
- 8
- NA
- 5
- An error
What does pmin(c(1, 6), c(4, 3)) return?
- 1
- c(1, 3)
- c(4, 6)
- 3