如何将矩阵转换为R中的二进制矩阵?
要将矩阵转换为二进制矩阵,我们可以使用as.matrix函数并将矩阵转换为逻辑矩阵,然后将0添加到大于0的值。例如,如果我们有一个名为M的矩阵,则可以使用以下命令将其转换为二进制矩阵命令-
as.matrix((M<0)+0)
查看以下示例,并尝试在休息时间进行操作以了解其工作原理。
示例1
M1<-matrix(rpois(40,1),ncol=2) M1输出结果
[,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
例2
M2<-matrix(rpois(80,2),ncol=4) M2输出结果
[,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