Darren J. Fitzpatrick
Darren J. Fitzpatrick

Reputation: 7409

R - return position of element in matrix?

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?

Upvotes: 25

Views: 56977

Answers (2)

Ramnath
Ramnath

Reputation: 55695

Here is one approach

mat = matrix(rnorm(9), 3, 3)
which(mat !=0, arr.ind = T)

Upvotes: 51

Richie Cotton
Richie Cotton

Reputation: 121057

m <- matrix(c(0, 1, 1, 0), nrow = 2)
which(m != 0)

or maybe

which(m != 0, TRUE)

Upvotes: 19

Related Questions