6

Suppose I have the vector ["a","b","c"], then I'd like to create a list of vectors of all the unique combinations, of all sizes (order does not matter):

["a"]
["b"]
["c"]
["a","b"]
["a","c"]
["b","c"]
["a","b","c"]

How can I do this in R?

CodeGuy
  • 28,427
  • 76
  • 200
  • 317

1 Answers1

17

We can try with combn

do.call("c", lapply(seq_along(v1), function(i) combn(v1, i, FUN = list)))

data

v1 <- letters[1:3]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • This does not return an array of arrays though. – CodeGuy Oct 14 '16 at 18:01
  • 2
    @CodeGuy What you have showed is a structure in another language. In R, vector structure is not as the one you showed. Also, in `R`, array can be either matrix (2 dimensional) or higher dimensions (with lengths equal). However, a `list` can accomodate vectors of different length. THat is the reason I place the vectors in a `list` – akrun Oct 14 '16 at 18:04
  • 1
    we found the Java progammer ;-), do you need it the way you outlined in your Question, if so just do this lapply(seq_along(v1), function(i) combn(v1, i, FUN = list)) – infominer Oct 14 '16 at 18:10
  • 3
    though I might add @akrun answer is better a data structure. – infominer Oct 14 '16 at 18:11