which, which.max, which.min

Basics

which is a function that takes a statement whose value evaluates to TRUE or FALSE, then returns the indices of the values that return TRUE. which.max and which.min are useful support functions that find the index of a vector’s maximum/minimum value.


Examples

Given a numeric vector, return the index of the maximum value.

Click to see solution
x <- c(1,-10, 2,4,-3,9,2,-2,4,8)
which.max(x)

# the above is a shortcut for which(x==max(x))
[1] 6

Given a vector, return the index of the positive values.

Click to see solution
x <- c(1,-10, 2,4,-3,9,2,-2,4,8)
which(x > 0)
[1]  1  3  4  6  7  9 10

Given a matrix, return the indexes (row and column) of the positive values.

Click to see solution
mat <- matrix(c(1, -10, 2, 4, -3, 9, 2, -2, 4, 8), ncol=2)
which(mat > 0, arr.ind = TRUE)
     row col
[1,]   1   1
[2,]   3   1
[3,]   4   1
[4,]   1   2
[5,]   2   2
[6,]   4   2
[7,]   5   2

If arr.ind = FALSE here, we would get one index per number found, which isn’t useful when we have two dimensions to search.