来自分组元素的组合

时间:2016-04-05 08:52:06

标签: r combinations

我有一个分组元素列表,我想要对这些元素进行所有可能的组合,但是我只想从每个组中获取一个元素。订单无关紧要。

vars_list <- list(Group1 = letters[1:5],  Group2 = letters[6:9],
                    Group3 = letters[10:11], Group4 = letters[12:15])

假设我想组合n = 2,n = 3,n = 4,其中n是我想要使用的组数。

当n =组数(Combinations from recursive lists)时,我找到了解决方法:

lengths <- c(1, 1, 1, 1)
combos <- expand.grid( mapply(function(element, n) combn(element, m=n,
FUN=paste0, collapse=""), vars_list, lengths, SIMPLIFY = F) )

我怎么能这样做n&lt;小组数量?

1 个答案:

答案 0 :(得分:1)

您可以使用combn获取n = 1,n = 2,n = 3和n = 4的所有群组,然后使用expand_grid

n = 2
apply(combn(1:length(vars_list), n), 2, function(x){expand.grid(vars_list[x])})

因此,对于n = 4,您将获得与您的问题相同的内容。这是你的意思吗?