How to convert a matrix to binary matrix in R?


To convert a matrix to binary matrix, we can use as.matrix function and converting the matrix to logical matrix then adding 0 to the values greater than 0. For example, if we have a matrix called M then it can be converted to a binary matrix using the command −

as.matrix((M<0)+0)

Check out the below examples and try to do it in breaks to understand how it works.

Example1

 Live Demo

M1<-matrix(rpois(40,1),ncol=2)
M1

Output

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

as.matrix((M1>0)+0)

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

Example2

 Live Demo

M2<-matrix(rpois(80,2),ncol=4)
M2

Output

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

as.matrix((M2>0)+0)

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

Updated on: 06-Mar-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements