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?
For instance, by generating some data for a 10 x 10:
> n=10;m=10
> mat = round(matrix(runif(m*n), m, n))
> 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
should always return that the matrix is binary, but changing it in one of the following ways:
> mat[1,1]=NA
> mat[1,1]=2
should return that the matrix is not binary.
Currently, I have been using in my function:
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")
}
}
}
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?
Thanks