As the title suggests in this post I’d like to explain something very basic and very essential. In R (as in other languages) you may do things in different ways. Sometimes it doesn’t matter which way you choose, but sometimes it really does. Once you’d need to extract elements from vector or matrix, another time you’d like to know the index of a specific element.
Say we have the following matrix:
x <- matrix( c(.007, 0.012, .022, 0.000, .005, 0.112, .027, 1.000, .037, .001, .061, .055), nrow=4, ncol=3, byrow=TRUE )
which looks like that:
[,1] [,2] [,3]
[1,] 0.007 0.012 0.022
[2,] 0.000 0.005 0.112
[3,] 0.027 1.000 0.037
[4,] 0.001 0.061 0.055
1. You can use a logical condition to extract elements of vector or matrix. In the following we’d like to know which elements in our matrix x are greater than 0.05
y <- x>0.05
The logical expression x > 0.05 will deliver a matrix (as x in our case is a matrix) with the same dimensions as x and which contains values of boolean type:
[,1] [,2] [,3]
[1,] FALSE FALSE FALSE
[2,] FALSE FALSE TRUE
[3,] FALSE TRUE FALSE
[4,] FALSE TRUE TRUE
and when you match the matrix x with the logical result matrix y:
you get a vector with the values matching our logical expression x > 0.05:
 1.000 0.061 0.112 0.055
2. Alternatively or for other purposes you may also use the which() function.
y <- which(x>0.05)
 7 8 10 12
As you can see it returns the index(es) of the match(es). And if you’re searching in a matrix as in our case, the result will be a vector of indexes, as the matrix is automatically converted to vector by R. That’s made in R’s default way by concatenating the columns and it leads to the conclusion that which(x) == which(as.vector(x)). If you however would rather like to know the row and colum index, you’ll need to set the function’s argument arr.in to TRUE.
y <- which(x>0.05, arr.in=TRUE)
[1,] 3 2
[2,] 4 2
[3,] 2 3
[4,] 4 3
Now that’s what I’d call a better result. And of course you can use the which function to extract elements of a vector or a matrix.
is the same as the shorter and memory saving way: