Given a matrix:
[,1] [,2] [1,] 0 0.0 [2,] -1 0.8
What is the quickest way in R to iterate over the matrix and return the position of all non-zero entries as an index?
The position of a matrix is the row number followed by the column number where that element is present. For example, in the matrix B = [131−10232] [ 1 3 1 − 1 0 2 3 2 ] , 1 is present in the 1st row and the 3rd column and hence we can write B₁, ₃ = 1 (or) B₁₃ = 1.
Use the match() Function to Find the Index of an Element in R. The match() function is very similar to the which() function. It returns a vector with the first index (if the element is at more than one position as in our case) of the element and is considered faster than the which() function.
Vectors are basic objects in R and they can be subsetted using the [ operator. The [ operator can be used to extract multiple elements of a vector by passing the operator an integer sequence.
A matrix function in R is a 2-dimensional array that has m number of rows and n number of columns. In other words, matrix in R programming is a combination of two or more vectors with the same data type. Note: It is possible to create more than two dimensions arrays with matrix function in R.
Here is one approach
mat = matrix(rnorm(9), 3, 3) which(mat !=0, arr.ind = T)
m <- matrix(c(0, 1, 1, 0), nrow = 2) which(m != 0)
or maybe
which(m != 0, TRUE)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With