How to check if a matrix in R is in binary form?


A binary matrix contains values in form of twos such as 0/1, 1/2, Yes/No etc. If we have a matrix that has some values and we expect that there are only two values in the whole matrix then we can check whether only those two values exist in the matrix or not. For example, if we have a matrix called M then we can check whether it contains only 0/1 in the matrix by using the command all(M %in% 0:1).

Example1

Live Demo

> M1<-matrix(sample(0:1,80,replace=TRUE),ncol=4)
> M1

Output

      [,1] [,2] [,3] [,4]
 [1,]    0    0    0    1
 [2,]    0    0    1    1
 [3,]    0    0    0    1
 [4,]    0    0    0    0
 [5,]    0    1    0    1
 [6,]    0    1    0    1
 [7,]    0    1    1    1
 [8,]    1    0    1    0
 [9,]    0    1    0    0
[10,]    0    1    1    0
[11,]    0    0    1    0
[12,]    1    1    1    1
[13,]    1    1    1    0
[14,]    1    1    1    1
[15,]    1    1    1    1
[16,]    0    0    0    0
[17,]    0    0    1    0
[18,]    1    1    1    1
[19,]    0    0    0    0
[20,]    0    1    0    1

Checking whether M1 contains only 0/1 or not −

> all(M1 %in% 0:1)

Output

[1] TRUE

Example2

Live Demo

> M2<-matrix(sample(1:2,40,replace=TRUE),ncol=2)
> M2

Output

      [,1] [,2]
 [1,]    2    2
 [2,]    1    2
 [3,]    2    2
 [4,]    2    1
 [5,]    2    2
 [6,]    2    1
 [7,]    2    2
 [8,]    1    1
 [9,]    2    2
[10,]    2    2
[11,]    1    2
[12,]    2    2
[13,]    1    2
[14,]    2    1
[15,]    2    1
[16,]    2    2
[17,]    2    2
[18,]    1    2
[19,]    1    2
[20,]    2    1

Checking whether M2 contains only 1/2 or not −

> all(M2 %in% 1:2)

Output

[1] TRUE

Example3

Live Demo

> M3<-matrix(sample(c("Yes","No"),40,replace=TRUE),ncol=2)
> M3

Output

      [,1]  [,2]
 [1,] "Yes" "No"
 [2,] "No"  "Yes"
 [3,] "Yes" "No"
 [4,] "Yes" "Yes"
 [5,] "No"  "No"
 [6,] "Yes" "Yes"
 [7,] "Yes" "Yes"
 [8,] "Yes" "No"
 [9,] "No"  "Yes"
[10,] "No"  "Yes"
[11,] "No"  "Yes"
[12,] "Yes" "No"
[13,] "Yes" "No"
[14,] "No"  "Yes"
[15,] "Yes" "No"
[16,] "No"  "No"
[17,] "No"  "Yes"
[18,] "No"  "No"
[19,] "No"  "No"
[20,] "Yes" "Yes"

Checking whether M3 contains only True/False or not −

> all(M3 %in% c("True","False"))

Output

[1] FALSE

Updated on: 06-Mar-2021

176 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements