来自不同容器的元素的所有可能组合(每个容器一个元素)
问题描述:
我有一个列表,其中每个元素都是一组数字。所有集合的长度都不同:
I have a list, where each element is a set of numbers. Lengths of all sets are different:
a <- list(1,c(2,3),c(4,5,6))
#> a
#[[1]]
#[1] 1
#[[2]]
#[1] 2 3
#[[3]]
#[1] 4 5 6
I' d想从每个集合中获得一个元素的所有可能组合。在此示例中,应为:
I'd like to get all possible combinations of one element from each set. In this example it should be:
1 2 4,1 2 5,1 2 6,1 3 4,1 3 5,1 3 6
1 2 4, 1 2 5, 1 2 6, 1 3 4, 1 3 5, 1 3 6
我觉得这里* apply-functions的某些组合会很有用,但无法弄清楚该怎么做。
I feel that some combination of *apply-functions here would be useful, but can't figure out how to do that.
答
我们可以使用 expand.grid
expand.grid(a)