-2

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
chippycentra
  • 3,396
  • 1
  • 6
  • 24
  • 1
    Does this answer your question? [Unique combination of all elements from two (or more) vectors](https://stackoverflow.com/questions/11388359/unique-combination-of-all-elements-from-two-or-more-vectors) – MrGumble Mar 08 '21 at 13:29
  • It is not the same thing, try their code and you will see you won't have the same output – chippycentra Mar 08 '21 at 13:31
  • 3
    What is the difference between entry 1 and entry 7 in your output? Aren't both 'A' from list1 and '1' from list2? – Sudaraka Mar 08 '21 at 13:41
  • 2
    It's hard to know how to help without a clear explanation of your logic. Calling `expand.grid` the way you've shown it does indeed give all combinations of the two vectors. Whatever the logic is that makes one (A,1) differ from another (A,1) should be here in the question – camille Mar 08 '21 at 16:27

1 Answers1

5

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
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81