1

I have a string of length 5. Each element of the string can take on two values 0 and 1.

I would like to write down all possible permutations.

For example:

0 0 0 0 0 
1 0 0 0 0
0 1 0 0 0
.
.
.
1 1 1 1 1 

There are 2^5 such combinations.

I know there is a command called combn but I do not know how to handle the fact that each digit can take on two possible values.

Henrik
  • 65,555
  • 14
  • 143
  • 159
upabove
  • 1,057
  • 3
  • 18
  • 29
  • If you want a fast solution you could also try `data.table` `CJ` function. I.e, `library(data.table); CJ(0:1, 0:1, 0:1, 0:1, 0:1)` – David Arenburg Aug 19 '14 at 08:39

2 Answers2

5

Perhaps not the best way to do it, but it works:

> expand.grid(0:1, 0:1, 0:1, 0:1, 0:1)
   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
talat
  • 68,970
  • 21
  • 126
  • 157
  • 1
    or `expand.grid(rep(list(0:1),5))` – akrun Aug 19 '14 at 07:44
  • Thanks, good point, @akrun – talat Aug 19 '14 at 07:57
  • thank you for this solution. the only problem is that it is very slow if you want to apply it to larger strings, for example 20. – upabove Aug 19 '14 at 08:06
  • 1
    @user2733997, I was sure hat there is some special function for this (that's why I wrote perhaps not the best way), just wanted to show a simple alternative that came to my mind. – talat Aug 19 '14 at 08:11
3

You can get your all 2^5 = 32 combinations by using :

install.packages('gtools')
library(gtools)
permutations(2,5,v=c(0,1),repeats.allowed=TRUE)
Sangram
  • 407
  • 1
  • 6
  • 18