Examples for 'base::which'


Which indices are TRUE?

Aliases: which arrayInd

Keywords: logic attribute

### ** Examples

which(LETTERS == "R")
[1] 18
which(ll <- c(TRUE, FALSE, TRUE, NA, FALSE, FALSE, TRUE)) #> 1 3 7
[1] 1 3 7
names(ll) <- letters[seq(ll)]
which(ll)
a c g 
1 3 7 
which((1:12)%%2 == 0) # which are even?
[1]  2  4  6  8 10 12
which(1:10 > 3, arr.ind = TRUE)
[1]  4  5  6  7  8  9 10
( m <- matrix(1:12, 3, 4) )
     [,1] [,2] [,3] [,4]
[1,]    1    4    7   10
[2,]    2    5    8   11
[3,]    3    6    9   12
div.3 <- m %% 3 == 0
which(div.3)
[1]  3  6  9 12
which(div.3, arr.ind = TRUE)
     row col
[1,]   3   1
[2,]   3   2
[3,]   3   3
[4,]   3   4
rownames(m) <- paste("Case", 1:3, sep = "_")
which(m %% 5 == 0, arr.ind = TRUE)
       row col
Case_2   2   2
Case_1   1   4
dim(m) <- c(2, 2, 3); m
, , 1

     [,1] [,2]
[1,]    1    3
[2,]    2    4

, , 2

     [,1] [,2]
[1,]    5    7
[2,]    6    8

, , 3

     [,1] [,2]
[1,]    9   11
[2,]   10   12
which(div.3, arr.ind = FALSE)
[1]  3  6  9 12
which(div.3, arr.ind = TRUE)
     row col
[1,]   3   1
[2,]   3   2
[3,]   3   3
[4,]   3   4
vm <- c(m)
dim(vm) <- length(vm) #-- funny thing with  length(dim(...)) == 1
which(div.3, arr.ind = TRUE)
     row col
[1,]   3   1
[2,]   3   2
[3,]   3   3
[4,]   3   4
## Don't show: 
dimnames(m) <- list(X = c("U", "V"), Z = c("y","z"), three = LETTERS[1:3])
wm <- which(m %% 3 == 0, arr.ind = TRUE)
vn <- vm; dimnames(vn) <- list(LETTERS[1:12])
wv <- which(vn %% 3 == 0, arr.ind = TRUE)

stopifnot(identical(wv, array(3L*(1:4), dim = c(4, 1),
                              dimnames = list(c("C", "F", "I", "L"), "dim1"))),
          identical(wm, array(c(1:2, 1:2, 2:1, 1:2, 1:3, 3L),
                              dim = 4:3,
                              dimnames = list(rep(c("U","V"),2),
                                              c("X", "Z", "three"))))
)
## End(Don't show)

[Package base version 4.2.3 Index]