How to convert a binary matrix to logical matrix in R?

R ProgrammingServer Side ProgrammingProgramming

A binary matrix contains values such as Yes or NO, 1 or 0, or any other two values that represents opposite mostly and the globally accepted logical values are FALSE and TRUE. Therefore, to convert a binary matrix to logical matrix, we can use ifelse function and convert the one category of binary variable to appropriate logical value and for the rest returns the left-out value. This is a very easy task in R, check out the below examples to understand how it can be done.

Example1

Live Demo

> M1<-matrix(sample(c("No","Yes"),40,replace=TRUE),nrow=20)
> M1

Output

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

Converting M1 to a logical matrix −

> M1[,]<-ifelse(M1 %in% c("No"),FALSE,TRUE)
> M1

Output

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

Example2

Live Demo

> M2<-matrix(sample(c("0","1"),40,replace=TRUE),nrow=20)
> M2

Output

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

Converting M2 to a logical matrix −

> M2[,]<-ifelse(M2 %in% c("0"),FALSE,TRUE)
> M2

Output

[,1] [,2]
[1,] "TRUE" "TRUE"
[2,] "FALSE" "TRUE"
[3,] "TRUE" "FALSE"
[4,] "FALSE" "FALSE"
[5,] "TRUE" "FALSE"
[6,] "TRUE" "TRUE"
[7,] "TRUE" "FALSE"
[8,] "FALSE" "TRUE"
[9,] "FALSE" "FALSE"
[10,] "FALSE" "FALSE"
[11,] "FALSE" "TRUE"
[12,] "FALSE" "FALSE"
[13,] "FALSE" "TRUE"
[14,] "FALSE" "FALSE"
[15,] "TRUE" "TRUE"
[16,] "FALSE" "TRUE"
[17,] "FALSE" "TRUE"
[18,] "TRUE" "FALSE"
[19,] "TRUE" "FALSE"
[20,] "TRUE" "FALSE"
raja
Published on 04-Mar-2021 08:32:28
Advertisements