开发者

R - return position of element in matrix?

开发者 https://www.devze.com 2023-03-16 00:40 出处:网络
Given a matrix: [,1] [,2] [1,]00.0 [2,]-10.8 W开发者_如何学Pythonhat is the quickest way in R to iterate over the matrix and return the position of all non-zero entries as an index?Here is one appr

Given a matrix:

      [,1] [,2]
[1,]    0  0.0
[2,]   -1  0.8

W开发者_如何学Pythonhat is the quickest way in R to iterate over the matrix and return the position of all non-zero entries as an index?


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消