which, which.max, which.min

which enables you to find the position of the elements that are TRUE in a logical vector.

which.max and which.min finds the location of the maximum and minimum, respectively, of a numeric (or logical) vector.

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)
[1] 6
# which.max is just shorthand 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
x <- matrix(c(1,-10, 2,4,-3,9,2,-2,4,8), ncol=2)
which(x>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