Home > Software design >  How to return only the "TRUE" values from sapply?
How to return only the "TRUE" values from sapply?

Time:10-16

I have a very large list of matrices and need to check if a new matrix is identical to any of the matrices in my existing list. My code looks like this:

sapply(matrix_list, identical, new_matrix)

I'm getting a very long list of False's, which is to be expected, but it's so long that I can't go through to see if there are any matches (TRUE's). Does anyone know how I can run this sapply function and only have it return TRUES, if there are any? Bonus points if you can tell me how I can locate the exact matrix that is associated with the TRUE.

Thank you!

CodePudding user response:

If you want to keep just true values then wrap the whole statement in which, here's a simple example:

which(sapply(letters, function(x) identical(x, "a")))
a 
1 

CodePudding user response:

like so:

## list of ten random 2 x 2 matrices:
haystack <- lapply(1:10, \(n) matrix(sample(1:100, 4), 2, 2))
## repeat 8th element of matrix:
haystack <- c(haystack, haystack[8])

## pick 8th element of matrix list as the new matrix
needle <- haystack[[8]]

which(
    sapply(haystack, \(i) identical(needle, i)) 
)
  • Related