二进制矩阵包含诸如“是”或“否”,“ 1”或“ 0”之类的值,或代表其他大多数相反值的任何其他两个值,并且全局接受的逻辑值为FALSE和TRUE。因此,要将二进制矩阵转换为逻辑矩阵,我们可以使用ifelse函数并将一类二进制变量转换为适当的逻辑值,而其余的则返回遗漏的值。在R中,这是一项非常简单的任务,请查看以下示例以了解如何完成。
> M1<-matrix(sample(c("No","Yes"),40,replace=TRUE),nrow=20) > M1输出结果
[,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"
将M1转换为逻辑矩阵-
> M1[,]<-ifelse(M1 %in% c("No"),FALSE,TRUE) > M1输出结果
[,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"
> M2<-matrix(sample(c("0","1"),40,replace=TRUE),nrow=20) > M2输出结果
[,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"
将M2转换为逻辑矩阵-
> M2[,]<-ifelse(M2 %in% c("0"),FALSE,TRUE) > M2输出结果
[,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"