28

I'd like to create a data.frame of all possible permutations of 10 variables that can be either 1 or 2

2*2*2*2*2*2*2*2*2*2 = 1024 # possible

1,1,1,1,1,1,1,1,1,1
1,2,1,1,1,1,1,1,1,1
1,2,2,1,1,1,1,1,1,1
1,2,2,2,1,1,1,1,1,1
...

Is there a "quick" way to do this in R?

Brandon Bertelsen
  • 43,807
  • 34
  • 160
  • 255
  • 2
    There's a `permutations` function in gregmisc I believe. You can coerce the resulting matrix to a data.frame. – Ari B. Friedman Feb 23 '12 at 23:23
  • 1
    Alternatively `combn` in `base`, combined with `unique(x, MARGIN=2)`. – jbaums Feb 23 '12 at 23:33
  • 1
    Not a permutation. [Permutations](https://en.wikipedia.org/wiki/Permutation) are rearrangements of objects. You cannot rearrange `1,1,1,1,1,1,1,1,1,1` into `1,2,1,1,1,1,1,1,1,1`, because the first string does not have any `2`. – liori May 05 '16 at 10:58
  • How should the question be edited to avoid calling these “permutations”? – randy Jul 09 '23 at 23:10

2 Answers2

34

how about this:

tmp = expand.grid(1:2,1:2,1:2,1:2,1:2,1:2,1:2,1:2,1:2,1:2)

or this (thanks Tyler):

x <- list(1:2)
tmp = expand.grid(rep(x, 10))
baha-kev
  • 3,029
  • 9
  • 33
  • 31
  • 17
    To type less code you could use: `x <- list(1:2);` `tmp = expand.grid(rep(x, 10))` – Tyler Rinker Feb 23 '12 at 23:30
  • I guess I'm asking too much, but it crashes when you try a large number like: expand.grid(0:451, 0:451, 0:451, 0:451). Is there any other way to do that? – vitor Jul 31 '13 at 22:05
  • 4
    @aguiar what is 452^4? -- that will be the number of combinations. That is almost 10 times the limit the length of a vector on 32-bit R, so you would need 64 bit R and perhaps 1 terrabyte of Ram! – mnel Aug 19 '13 at 23:25
0

Some people have asked the question regarding letters, such as here. The expand.grid solution is usually given, but I find this to be much simpler:

sapply(LETTERS[1:3], function(x){paste0(x, LETTERS[1:3])}) %>% c()
# [1] "AA" "AB" "AC" "BA" "BB" "BC" "CA" "CB" "CC"
abalter
  • 9,663
  • 17
  • 90
  • 145