R: Binary matrix for all possible unique results

How to create a binary matrix for all possible permutations of the “i” variables of X, where the “i” can be any number between 1 and infinite. The resulting matrix will have 2 ^ i unique rows.

For i = 2, the variables x1, x2, each with a possible value of 1 or 0, so the resulting matrix will be:

X1 X2 0 0 0 1 1 0 1 1 

Is there any function in R to generate?

I tried with the function below:

  matrix(rbinom(160, 1, 0.5),ncol=5,nrow=(2^5)) 

But the result does not show all possible values.

+4
source share
3 answers

you can use expand.grid :

  expand.grid(c(0,1),c(0,1)) Var1 Var2 1 0 0 2 1 0 3 0 1 4 1 1 

More generally, for example, with 5 columns, giving m :

 m <- as.data.frame(matrix(rbinom(5*2, 1, 0.5),ncol=5)) V1 V2 V3 V4 V5 1 0 1 1 0 0 2 0 1 1 0 0 dim(expand.grid(m)) 32 5 
+4
source

The fonction combinations of the hier.part package will do the job, I think.

 require(hier.part) combos(2)$binary [,1] [,2] [1,] 1 0 [2,] 0 1 [3,] 1 1 combos(3)$binary [,1] [,2] [,3] [1,] 1 0 0 [2,] 0 1 0 [3,] 0 0 1 [4,] 1 1 0 [5,] 1 0 1 [6,] 0 1 1 [7,] 1 1 1 

Except that you will need to add a “null” combination. NTN

+1
source

try it

 i =2 install.packages('gtools') library(gtools) permutations(2,i,v=c(0,1),repeats.allowed=TRUE) 
0
source

Source: https://habr.com/ru/post/1488020/


All Articles