Which indices are TRUE?

Give the TRUE indices of a logical object, allowing for array indices.

attribute, logic
which(x, arr.ind = FALSE, useNames = TRUE) arrayInd(ind, .dim, .dimnames = NULL, useNames = FALSE)
a logical vector or array. NAs are allowed and omitted (treated as if FALSE).
logical; should array indices be returned when x is an array?
integer-valued index vector, as resulting from which(x).
dim(.) integer vector
optional list of character dimnames(.), of which only .dimnames[[1]] is used.
logical indicating if the value of arrayInd() should have (non-null) dimnames at all.

If arr.ind == FALSE (the default), an integer vector with length equal to sum(x), i.e., to the number of TRUEs in x; Basically, the result is (1:length(x))[x].If arr.ind == TRUE and x is an array (has a dim attribute), the result is arrayInd(which(x), dim(x), dimnames(x)), namely a matrix whose rows each are the indices of one element of x; see Examples below.

See Also

Logic, which.min for the index of the minimum or maximum, and match for the first index of an element in a vector, i.e., for a scalar a, match(a, x) is equivalent to min(which(x == a)) but much more efficient.

  • which
  • arrayInd
library(base) which(LETTERS == "R") which(ll <- c(TRUE, FALSE, TRUE, NA, FALSE, FALSE, TRUE)) #> 1 3 7 names(ll) <- letters[seq(ll)] which(ll) which((1:12)%%2 == 0) # which are even? which(1:10 > 3, arr.ind = TRUE) ( m <- matrix(1:12, 3, 4) ) div.3 <- m %% 3 == 0 which(div.3) which(div.3, arr.ind = TRUE) rownames(m) <- paste("Case", 1:3, sep = "_") which(m %% 5 == 0, arr.ind = TRUE) dim(m) <- c(2, 2, 3); m which(div.3, arr.ind = FALSE) which(div.3, arr.ind = TRUE) vm <- c(m) dim(vm) <- length(vm) #-- funny thing with length(dim(...)) == 1 which(vm %% 3 == 0, arr.ind = TRUE)
Documentation reproduced from package base, version 3.0.3, License: Part of R 3.0.3

Community examples

Looks like there are no examples yet.