Index of the first minimum or maximum value of a vector in R with which.max and which.min
The which.max
and which.min
functions are base R functions that return the index of the first minimum or maximum value of a numeric or logical vector, discarding missing and NaN values.
The which.max
function
In order to get the index of the maximum value of a numeric vector you can input that vector to the which.max
function and the index will be returned.
x <- c(10, 23, 125, 20, 1)
# Which is the position of the maximum value?
which.max(x)
3
Note that this function can also be used with a boolean vector. In this case, the function will return the index of the first TRUE
.
y <- c(FALSE, TRUE, TRUE, FALSE)
# Which is the position of the first TRUE?
which.max(y)
2
Return the maximum value
As the function returns an index, you can also get the maximum value indexing the output to the original vector, as shown in the example below. Note that you could also make use of the max
function to get the maximum value.
x <- c(10, 23, 125, 20, 1)
m <- which.max(x)
x[m]
125
The which.min
function
If instead of the index of the maximum value you want to obtain the index of the minimum value of a vector you will need to use the which.min
function.
x <- c(10, 23, 125, 20, 1)
# Which is the position of the minimum value?
which.min(x)
5
In this scenario, if the vector is boolean the function will return the index of the first FALSE
.
y <- c(FALSE, TRUE, TRUE, FALSE)
# Which is the position of the first FALSE?
which.min(y)
1
Return the minimum value
If you want to return the minimum value, you can index the vector as in the example below. Recall that the min
function will return the same result.
x <- c(10, 23, 125, 20, 1)
m <- which.min(x)
x[m]
1