'How can I check if a matrix is an element of a list of matrices? in R

I'm pretty new to programming in R.

I have a matrix of numbers mat, as well as a list of matrices matlist. I want to check if the matrix mat matches with (i.e., is identical to) any element of matlist. I tried the %in% method but this doesn't give me the output I hope for.

Here's something like my code.

mat <- rbind(c(0,1),
             c(1,0))
mat2 <- rbind(c(1,1),
              c(1,0))
matlist <- vector(mode="list", 2)
matlist[[1]] <- mat
matlist[[2]] <- mat2

If I then try mat %in% matlist I get: FALSE FALSE FALSE FALSE

I'm looking for an expression like this which will evaluate to TRUE.

This seems like it should be really simple but I can't find an answer!



Solution 1:[1]

You could try something like:

sapply(matlist,function(x) identical(x,mat)), or as @jbaums mentions below: sapply(matlist,identical,mat)

Or build yourself a custom function to check any matrix in any matrix list:

matrix_is_in <- function(my_mat, my_mat_list) {
      sapply(my_matlist, function(x) identical(x, my_mat))
}

Then try it out:

matrix_is_in(mat,matlist)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1