user3593717
user3593717

Reputation: 131

Finding all possible ways to select 'n' elements from 'n' lists

I would like to find the most computationally efficient way to get all possible ways to take 'n' values from 'n' separate lists, where each list may have 1 or more elements, in R. I'll illustrate with an example.

Suppose I have a list of lists (in my example, specifically a list of four lists):

ll <- list(list(1), list(2), list(1,3), list(2,4))

I want to get all the ways I can sample one value from each of the four lists in this list of lists. In this case, the possible sets of values would be:

c(1, 2, 1, 2)
c(1, 2, 1, 4)
c(1, 2, 3, 2)
c(1, 2, 3, 4)

The sets of values may be returned as a list of lists, a matrix, a data frame, whatever. I would just like to get each possible set of 'n' values that can be taken from 'n' lists, one value from each list. I figured I'd have to use some kind of for loop to do this, but any suggestions are welcome. Thanks.

Upvotes: 0

Views: 238

Answers (1)

steveb
steveb

Reputation: 5532

You could try something like the following

expand.grid(ll)

#   Var1 Var2 Var3 Var4
# 1    1    2    1    2
# 2    1    2    3    2
# 3    1    2    1    4
# 4    1    2    3    4

Upvotes: 1

Related Questions