如何在 R 中将二进制矩阵转换成逻辑矩阵?


二进制矩阵包含是或否、1 或 0 之类的值,或其他表示相反情况的值,而公认的逻辑值为假或真。因此,要将二进制矩阵转换成逻辑矩阵,我们可使用 ifelse 函数,并将二进制变量的一类转换成适当的逻辑值,其他值返回未列出的值。这是 R 中一个非常简单的任务,查看以下示例以了解如何执行此操作。

示例 1

实时演示

> 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"

示例 2

实时演示

> 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"

更新日期: 04-Mar-2021

837 次浏览

启动您的 事业

完成课程以获得认证

立即开始
广告