如何检查R中的矩阵是否为二进制形式?
二进制矩阵包含以2的形式表示的值,例如0/1、1/2,是/否等。如果我们有一个包含一些值的矩阵,并且期望整个矩阵中只有两个值,则可以检查矩阵中是否仅存在这两个值。例如,如果我们有一个名为M的矩阵,则可以使用all(M%in%0:1)命令检查矩阵中是否仅包含0/1。
例1
> M1<-matrix(sample(0:1,80,replace=TRUE),ncol=4) > M1输出结果
[,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
检查M1是否仅包含0/1-
> all(M1 %in% 0:1)输出结果
[1] TRUE
例2
> M2<-matrix(sample(1:2,40,replace=TRUE),ncol=2) > M2输出结果
[,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
检查M2是否仅包含1/2-
> all(M2 %in% 1:2)输出结果
[1] TRUE
范例3
> M3<-matrix(sample(c("Yes","No"),40,replace=TRUE),ncol=2) > M3输出结果
[,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"
检查M3是否仅包含True/False-
> all(M3 %in% c("True","False"))输出结果
[1] FALSE