R: return array index of partial string match -
suppose have 10x10 matrix populated 1:100. want search numbers ending in '0', , want [i,j]
index numbers. tried which(..., arr.ind=t)
, couldn't find function works it. tried grep('0$', ...)
returns single index of matrix vector. suppose possible turn number binary index, there simpler way?
x <- t(matrix(1:100,nrow=10,ncol=10)) # output: # [1,] 1 10 # [2,] 2 10 # ... # [10,] 10 10
we can convert grepl
output matrix
same dim
original 'x' , use which
arr.ind=true
.
which(`dim<-`(grepl('0$', x), dim(x)), arr.ind=true) # row col # [1,] 1 10 # [2,] 2 10 # [3,] 3 10 # [4,] 4 10 # [5,] 5 10 # [6,] 6 10 # [7,] 7 10 # [8,] 8 10 # [9,] 9 10 #[10,] 10 10
or without changing dim
, grepl
output logical
vector, negate (!
) true becomes false , false true, multiply original matrix output in matrix
. replace values in 'x' ends '0' 0. negate (!
) again 0
gets convert true , others false. use which
, index corresponding true values.
which(!x*(!(grepl('0$', x))), arr.ind=true)
Comments
Post a Comment