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

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

The following function is a variant of %in% that behaves more consistently with ==, this include the behavior with matrices, but also other classes, and it makes sure NAs stay NAs.

`%in{}%` <- function(x, table) {
  table <- unlist(table)
  if (is.list(x) && !is.data.frame(x)) {
    x <- switch(
      typeof(table),
      logical = as.logical(x),
      integer = as.integer(x),
      double = as.double(x),
      complex = as.complex(x),
      character = as.character(x),
      raw = as.raw(x))
  }

  # convert to character
  if (is.factor(table)) {
    table <- levels(table)[table]
  }
  if (is.data.frame(x)){
      res <- sapply(x, `%in%`, table)
    } else if (is.matrix(x)){
    res <- apply(x, 2, `%in%`, table)
  } else {
    res <- x %in% table
  }
  res[is.na(x)] <- NA
  res
}

m <- matrix(c(0, "a", "gamma", 0, 0.5, 0, 0, 0, 0), ncol = 3)
candidates <- c("a", "gamma", "b")
which(m %in{}% candidates, arr.ind = TRUE)
#>      row col
#> [1,]   2   1
#> [2,]   3   1

Tags:

Matrix

R

Subset