arrays - How to find a row or column under specific conditions in a matrix in R -
this question has answer here:
for example, if have matrix or array following format
how can find index of rows or columns have numbers between 10 20 inside ?
m = array(c(1,1,12,34,0,19,15,1,0,17,12,0,21,1,11,1), dim=c(4,4))
and, also, not allowed use or while loops this. thing matrix or array may have more 2 dimensions. if method can apply multi-dimensional matrix or array, better me. thanks.
instead of trying find index of qualified single elements, need find rows or columns in elements between interval.
in example, hope have result telling me row number 3 row numbers within row between 10 20.
use which(..., arr.ind = true)
. here assume between means 10 , 20 non-inclusive
which(m > 10 & m < 20, arr.ind = true) # row col # [1,] 3 1 # [2,] 2 2 # [3,] 3 2 # [4,] 2 3 # [5,] 3 3 # [6,] 3 4
this work on 3-dimensional arrays (and higher).
## 3 dimensions dim(m) <- c(2, 4, 2) which(m > 10 & m < 20, arr.ind = true) # dim1 dim2 dim3 # [1,] 1 2 1 # [2,] 2 3 1 # [3,] 1 4 1 # [4,] 2 1 2 # [5,] 1 2 2 # [6,] 1 4 2 ## 4 dimensions dim(m) <- rep(2, 4) which(m > 10 & m < 20, arr.ind = true) # dim1 dim2 dim3 dim4 # [1,] 1 2 1 1 # [2,] 2 1 2 1 # [3,] 1 2 2 1 # [4,] 2 1 1 2 # [5,] 1 2 1 2 # [6,] 1 2 2 2 ## ... , on
note: include 10 , 20, use m >= 10 & m <= 20
data:
m <- structure(c(1, 1, 12, 34, 0, 19, 15, 1, 0, 17, 12, 0, 21, 1, 11, 1), .dim = c(4l, 4l))
update: edit, can find row numbers values between 10 , 20 with
which(rowsums(m >= 10 & m <= 20) == ncol(m)) # [1] 3
Comments
Post a Comment