Determining Whether a Matrix Has At Least One Zero Element

matrix, r

Solution

The warning is generated because you're presenting a vector of logical to `if`, which expects a single value. `any` is a function to tell if any of the logical values are `TRUE`:

any(A==0)
## [1] TRUE
any(B==0)
## [1] FALSE

There's also a function `all` which determines if all of the values in a logical vector are `TRUE`.

Problem

I'm sure this is trivial - nonetheless, any help would be appreciated. The problem is simple: given a matrix, I'd like to get `TRUE` if the matrix in question has at least one element equal to zero. So, checking ``` A <- matrix(c(1, 2, 3, 4, 5, 0), nrow = 2, ncol = 3, byrow = TRUE) > A [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 0 ``` would return `TRUE`, while ``` B <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3, byrow = TRUE) > B [,1] [,2] [,3] [1,] 1 2 3 [2,] 4 5 6 ``` would return `FALSE`. Something like ``` if ( A == 0 ) { cat("\nZero detected")} ``` gives a warning. Is there a simple way to do this?

Original source