来自分组元素的组合
Combinations from grouped elements
我有一个分组元素列表,我想对这些元素进行所有可能的组合,但是我只想从每个组中取出一个元素。顺序无关紧要。
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 < 组数执行此操作?
您可以使用 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,你会得到与你的问题相同的结果。这是你的意思吗?
我有一个分组元素列表,我想对这些元素进行所有可能的组合,但是我只想从每个组中取出一个元素。顺序无关紧要。
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 < 组数执行此操作?
您可以使用 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,你会得到与你的问题相同的结果。这是你的意思吗?