Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find array index of elements of a matrix that match a value in a vector of candidate values

Tags:

r

matrix

subset

I have been googeling and stackoverflowing this for a while but I cant seem to find the right answer.

I have a matrix that contains different characters strings like "a", or "gamma", or even numbers coerced to characters.

How do I get the array indices of matrix m if an element of m matches a value in a vector of candiate values (note that these values could be any character string). Here is what I tried. I though which(m %in% ...) would do it but it doesnt return what I expected.

m <- matrix(c(0, "a", "gamma", 0, 0.5, 0, 0, 0, 0), ncol = 3)
m
#>      [,1]    [,2]  [,3]
#> [1,] "0"     "0"   "0" 
#> [2,] "a"     "0.5" "0" 
#> [3,] "gamma" "0"   "0"

which(m == "a", arr.ind = TRUE) # as expected
#>      row col
#> [1,]   2   1

which(m == "a" | m == "gamma", arr.ind = TRUE) # also obvious
#>      row col
#> [1,]   2   1
#> [2,]   3   1

candidates <- c("a", "gamma", "b")
which(m %in% candidates, arr.ind = TRUE) # not what I expected
#> [1] 2 3

Created on 2019-09-11 by the reprex package (v0.3.0)

  • The result I want is the row and column index of elements in m that match a value in candiates.
  • I prefer a base R solution if possible.

Any help?

like image 363
Manuel R Avatar asked Sep 11 '19 15:09

Manuel R


People also ask

How do you find the index of an element in a matrix?

To find the index of the element in the array, you can use the find() function. Using the find() function you can find the indices and the element from the array. The find() function returns a vector containing the data.

How do you find the index of a matrix in Matlab?

k = find( X , n ) returns the first n indices corresponding to the nonzero elements in X . k = find( X , n , direction ) , where direction is 'last' , finds the last n indices corresponding to nonzero elements in X .

How do you find the index of an element in an array in Matlab?

How do you find the index of a value in a vector in MATLAB? k = find( X ) returns a vector containing the linear indices of each nonzero element in array X . If X is a vector, then find returns a vector with the same orientation as X .


1 Answers

The problem is that %in% doesn't preserve the dimensions of the input. You can write your own function that would do that. For example

`%matin%` <- function(x, table) {
  stopifnot(is.array(x))
  r <- x %in% table
  dim(r) <- dim(x)
  r
}

candidates <- c("a", "gamma", "b")
which(m %matin% candidates, arr.ind = TRUE)
#      row col
# [1,]   2   1
# [2,]   3   1
like image 176
MrFlick Avatar answered Sep 22 '22 01:09

MrFlick