R - return position of element in matrix?

53,291

Solution 1

Here is one approach

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

Solution 2

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

or maybe

which(m != 0, TRUE)
Share:
53,291

Related videos on Youtube

Darren J. Fitzpatrick
Author by

Darren J. Fitzpatrick

Updated on July 09, 2022

Comments

  • Darren J. Fitzpatrick
    Darren J. Fitzpatrick almost 2 years

    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?

    • hadley
      hadley almost 13 years
      Your question should be "which is the fastest way?" Then it would also answer itself ;)
    • Chris Beeley
      Chris Beeley about 12 years
      I've been chuckling about this "which is the fastest way" joke for two days. I've made it into a blog post I like it so much.
  • IRTFM
    IRTFM almost 13 years
    @Cotton: Ramnath's answer added the very used information that there was an addition parameter to which that produces matrix-oriented output. So I didn't see him as agreeing so much as doing a better job of inferring what the OP wanted.
  • Gavin Simpson
    Gavin Simpson almost 13 years
    @DWin Err, isn't that what the TRUE in @Ritchie's R code after "or maybe" is doing? Poor form in a teaching environment to not name arguments, but the two Answers are the same.
  • Richie Cotton
    Richie Cotton almost 13 years
    @DWin: It's okay, no need to explain. You obviously love Ramnath more than me. I won't spend the afternoon sitting in the corner of the office, crying and drawing pictures of upvoted answers.