Search code examples
rcombinationspermutation

Generate list of all possible combinations of elements of vector


I am trying to generate all possible combinations of 0 and 1's in a vector of length 14. Is there an easy way of getting that output as a list of vectors, or even better, a dataframe?

To demonstrate better what I am looking for, let's suppose that I only want a vector of length 3. I would like to be able to generate the following:

 (1,1,1), (0,0,0), (1,1,0), (1,0,0), (1,0,1), (0,1,0), (0,1,1), (0,0,0)

Solution

  • You're looking for expand.grid.

    expand.grid(0:1, 0:1, 0:1)
    

    Or, for the long case:

    n <- 14
    l <- rep(list(0:1), n)
    
    expand.grid(l)