R - return position of element in matrix?

余生颓废 提交于 2020-01-09 09:01:46

问题


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?


回答1:


Here is one approach

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



回答2:


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

or maybe

which(m != 0, TRUE)


来源:https://stackoverflow.com/questions/6522134/r-return-position-of-element-in-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!