which.max / which.min()
which.min(x) / which.max(x) Returns:
integer · Updated March 13, 2026 · Base Functions base statistics max min indices
which.min() and which.max() are base R functions that return the index of the minimum and maximum values in a vector respectively. They are essential tools for finding the position of extreme values without having to manually scan through entire vectors.
Syntax
which.min(x)
which.max(x)
Parameters
| Parameter | Type | Description |
|---|---|---|
x | numeric or character | A vector of numeric or character values |
Examples
Basic usage with numeric vectors
scores <- c(85, 92, 78, 88, 95)
# Find position of minimum value
which.min(scores)
# [1] 3
# Find position of maximum value
which.max(scores)
# [1] 5
Using with character vectors
fruits <- c("apple", "banana", "cherry", "date")
# Find first alphabetically
which.min(fruits)
# [1] 1 (apple)
# Find last alphabetically
which.max(fruits)
# [1] 4 (date)
Finding extreme values with their positions
temperatures <- c(72, 68, 75, 71, 69, 82, 77)
# Get the index of the coldest and warmest days
coldest <- which.min(temperatures)
warmest <- which.max(temperatures)
# Extract the values
temperatures[coldest]
# [1] 68
temperatures[warmest]
# [1] 82
Using with data frames
df <- data.frame(
product = c("A", "B", "C", "D"),
price = c(29.99, 45.00, 19.99, 35.50)
)
# Find cheapest product
df[which.min(df)]
# [1] "C"
# Find most expensive product
df[which.max(df)]
# [1] "B"
Common Patterns
Combining with order() for sorting
values <- c(5, 2, 8, 1, 9, 3)
# Get indices of min and max
c(min = which.min(values), max = which.max(values))
# min max
# 4 5
Finding extremes in matrices
m <- matrix(1:9, nrow = 3)
# [,1] [,2] [,3]
# [1,] 1 4 7
# [2,] 2 5 8
# [3,] 3 6 9
which.min(m)
# [1] 1
which.max(m)
# [1] 9
Handling NA values
data <- c(1, NA, 5, 2, NA, 8)
# NA values are ignored by default
which.min(data)
# [1] 1
which.max(data)
# [1] 6