title: How to efficiently check if a matrix is in binary form (e.g. all 1's or 0's)?
body: <p>I have a function that take an m x n sized (potentially) binary matrix as input, and I would like to return an error handling if the matrix contains a number that is not 0 or 1, or is NA. How can I check this efficiently?</p>
  
  <p>For instance, by generating some data for a 10 x 10:</p>
  
  <pre><code>&gt; n=10;m=10
  &gt; mat = round(matrix(runif(m*n), m, n))
  &gt; mat
          [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
   [1,]    0    1    0    1    1    0    1    0    1     0
   [2,]    0    0    0    0    0    0    0    0    0     1
   [3,]    1    1    0    1    1    0    0    1    1     0
   [4,]    1    1    1    1    0    1    0    0    1     1
   [5,]    1    1    1    0    0    1    1    1    0     1
   [6,]    1    0    1    0    0    0    0    1    0     0
   [7,]    0    0    0    1    0    1    1    1    1     0
   [8,]    0    0    0    1    0    1    1    1    1     1
   [9,]    0    0    1    1    0    1    1    1    1     1
  [10,]    1    0    1    1    0    0    0    0    1     1
  </code></pre>
  
  <p>should always return that the matrix is binary, but changing it in one of the following ways:</p>
  
  <pre><code>&gt; mat[1,1]=NA
  &gt; mat[1,1]=2
  </code></pre>
  
  <p>should return that the matrix is not binary.</p>
  
  <p>Currently, I have been using in my function:</p>
  
  <pre><code>for(i in 1:nrow(mat))
  {
      for(j in 1:ncol(mat))
      {
        if(is.na(mat[i,j])|(!(mat[i,j] == 1 | mat[i,j] == 0)))
        {
          stop("Data must be only 0s, 1s")
        }
      }
  }
  </code></pre>
  
  <p>but it seems awfully slow and inefficient to individually check every value for large matrices. Is there a clever, easy way to do this I'm missing? </p>
  
  <p>Thanks</p>