简体   繁体   中英

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 (ie, 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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM