RudiSophieson
RudiSophieson

Reputation: 271

R - row-wise combinations of two lists

assume that I have two lists of the same length.

l1 <- list(c("a", "b", "c"), "d")
l2 <- list(c("e", "f"), c("g", "h", "i"))

Each row/element of a list can be seen as a specific pair. So in this example the two vectors

c("a", "b", "c")
c("e", "f")

"belong together" and so do the two others.

I need to get all the possible combinations/permutations of those two vectors with the same index.

I know that I can use expand.grid(c("a", "b", "c"), c("e", "f")) for two vectors, but I'm struggling to do this over both lists iteratively. I tried to use mapply(), but couldn't come up with a solution.

The preferred output can be a dataframe or a list containing all possible row-wise combinations. It's not necessary to keep the information of the "source pair". I'm just interested in the combinations.

So, a possible output could look like this:

  l1 l2
1  a  e
2  b  e
3  c  e
4  a  f
5  b  f
6  c  f
7  d  g
8  d  h
9  d  i

Upvotes: 3

Views: 534

Answers (1)

Roland
Roland

Reputation: 132706

You can use Map to loop over the list elements and then use rbind:

do.call(rbind, Map(expand.grid, l1, l2))
#  Var1 Var2
#1    a    e
#2    b    e
#3    c    e
#4    a    f
#5    b    f
#6    c    f
#7    d    g
#8    d    h
#9    d    i

Map is just mapply with different defaults.

Upvotes: 4

Related Questions