How to create combinations of 0 and 1 with fixed number of 1s in each row in an R data frame?

R ProgrammingServer Side ProgrammingProgramming

To create the combinations of 0 and 1 data frame, we can use expand.grid function along with the rep function. If we want to create combination of 0 and 1 with fixed number of 1’s in each row then rowSums functions can be used with the appropriate sum value. For example, to have rows containing less than three 1’s, the rowSums will be extracted from grid for the same.

Example1

 Live Demo

First<−expand.grid(rep(list(0:1),3))
First

Output

Var1 Var2 Var3
1 0 0 0
2 1 0 0
3 0 1 0
4 1 1 0
5 0 0 1
6 1 0 1
7 0 1 1
8 1 1 1

Creating combinations having number of 1s in each row less than or equal to 2 −

Example

First<−First[rowSums(First)<3,]
First

Output

Var1 Var2 Var3
1 0 0 0
2 1 0 0
3 0 1 0
4 1 1 0
5 0 0 1
6 1 0 1
7 0 1 1

Example2

 Live Demo

Second<−expand.grid(rep(list(0:1),4))
Second

Output

Var1 Var2 Var3 Var4
1  0  0 0 0
2  1  0 0 0
3  0   1 0 0
4  1   1 0 0
5  0   0 1 0
6  1  0 1 0
7  0   1 1 0
8  1   1 1 0
9  0 0 0 1
10 1 0 0 1
11 0 1 0 1
12 1 1 0 1
13 0 0 1 1
14 1 0 1 1
15 0 1 1 1
16 1 1 1 1

Example

Second<−Second[rowSums(Second)<4,]
Second

Output

Var1 Var2 Var3 Var4
1 0 0 0 0
2 1 0 0 0
3 0 1 0 0
4 1 1 0 0
5 0 0 1 0
6 1 0 1 0
7 0 1 1 0
8 1 1 1 0
9 0 0 0 1
10 1 0 0 1
11 0 1 0 1
12 1 1 0 1
13 0 0 1 1
14 1 0 1 1
15 0 1 1 1

Example3

 Live Demo

Third<−expand.grid(rep(list(0:1),5))
Third

Output

Var1 Var2 Var3 Var4 Var5
1 0 0 0 0 0
2 1 0 0 0 0
3 0 1 0 0 0
4 1 1 0 0 0
5 0 0 1 0 0
6 1 0 1 0 0
7 0 1 1 0 0
8 1 1 1 0 0
9 0 0 0 1 0
10 1 0 0 1 0
11 0 1 0 1 0
12 1 1 0 1 0
13 0 0 1 1 0
14 1 0 1 1 0
15 0 1 1 1 0
16 1 1 1 1 0
17 0 0 0 0 1
18 1 0 0 0 1
19 0 1 0 0 1
20 1 1 0 0 1
21 0 0 1 0 1
22 1 0 1 0 1
23 0 1 1 0 1
24 1 1 1 0 1
25 0 0 0 1 1
26 1 0 0 1 1
27 0 1 0 1 1
28 1 1 0 1 1
29 0 0 1 1 1
30 1 0 1 1 1
31 0 1 1 1 1
32 1 1 1 1 1

Example

Third<−Third[rowSums(Third)<3,]
Third

Output

1 0 0 0 0 0
2 1 0 0 0 0
3 0 1 0 0 0
4 1 1 0 0 0
5 0 0 1 0 0
6 1 0 1 0 0
7 0 1 1 0 0
9 0 0 0 1 0
10 1 0 0 1 0
11 0 1 0 1 0
13 0 0 1 1 0
17 0 0 0 0 1
18 1 0 0 0 1
19 0 1 0 0 1
21 0 0 1 0 1
25 0 0 0 1 1
raja
Updated on 08-Feb-2021 12:48:13

Advertisements