我有一个分组元素的列表,我想对这些元素进行所有可能的组合,但是我只想从每个组中获取一个元素。秩序并不重要。
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=number of groups (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个组做到这一点?
发布于 2016-04-05 09:19:18
您可以使用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,您将得到与您的问题相同的结果。你是这个意思吗?
https://stackoverflow.com/questions/36421490
复制相似问题