rdplyrcombinations

Generate a dataframe with all possible combinations between two lists


Hello I have two lists:

list1<-c("A","B")
list2<-c(1,2,3)

and i would like to get all possible combinations and save it into a dataframe such as :

with a colum called Possibilities which refers to the name of the possibilities.

list1 list2 Possibilities
A     1     P1
B     1     P1
A     2     P2
B     2     P2
A     3     P3
B     3     P3
A     1     P4
B     2     P4
A     2     P5
B     1     P5
A     3     P6
B     1     P6
A     1     P7
B     3     P7
A     2     P8
B     3     P8
A     3     P9
B     2     P9

The solution :

> expand.grid(list1,list2)

did not what I whant since it gives:

  Var1 Var2
1    A    1
2    B    1
3    A    2
4    B    2
5    A    3
6    B    3

Solution

  • I think you can try expand.grid like below

    data.frame(
      lst1 = list1,
      lst2 = c(t(rev(expand.grid(rep(list(list2), length(list1)))))),
      Possibilities = paste0("P", rep(seq(length(list2)^length(list1)), each = length(list1)))
    )
    

    which gives

       lst1 lst2 Possibilities
    1     A    1            P1
    2     B    1            P1
    3     A    1            P2
    4     B    2            P2
    5     A    1            P3
    6     B    3            P3
    7     A    2            P4
    8     B    1            P4
    9     A    2            P5
    10    B    2            P5
    11    A    2            P6
    12    B    3            P6
    13    A    3            P7
    14    B    1            P7
    15    A    3            P8
    16    B    2            P8
    17    A    3            P9
    18    B    3            P9