-1

我试图弄清楚在排除某些选定组合后如何计算 combn 函数返回的组合数量。比方说,我们有一个向量 c("var1","var2","var3","var4","var5") ,我想得到这个向量的所有元素组合,除了那些包含 c(" var4","var5")。这是代码:

vector <- c("var1","var2","var3","var4","var5")
exclude <- matrix(c("var4","var5"),1,2)

for(i in 1:length(vector)){
  comb <- combn(vector,i)
  for(j in 1:ncol(comb)){
    newcomb <- c(comb[,j])
    if (any(as.logical("FALSE"),apply(exclude, 1, function(x) all(x %in% newcomb)))) {next}
      else {print(newcomb)}}
}

从 combn 函数返回的组合数没有任何减少是 31。它被认为是:

f <- function(nvars){
  a <- NULL
  for (i in 1:nvars){
    a[i] <- choose(nvars,i)}
  return(sum(a))}
f(5)

任何关于如何获得减少组合数量的建议(对于 5 个变量并排除同时包含“var4”和“var5”的组合,它应该是 23)。谢谢!

4

3 回答 3

0

这将计算任何输入的组合数量,vector并且exclude(它基于您在问题中的循环)......

sum(sapply(seq_along(vector),                   #sum for all combination lengths...
    function(i) sum(apply(combn(vector, i), 2,  #...the sum for all combinations...
        function(y) !any(apply(exclude, 1,      #...the value for each row of exclude...
            function(x) all(x %in% y)))))))     #...whether combn doesn't contain exclude row

[1] 71 #for the example you give
于 2017-08-06T10:03:08.140 回答
-1

我们遍历 的序列,通过vector指定' combnm' 作为序列值得all%in%!unlistlistsum

sum(unlist(lapply(seq_along(vector), function(i) combn(vector, i,
         FUN = function(x) !all(c(exclude) %in% x)))))
#[1] 23
于 2017-08-05T10:44:28.693 回答
-1

我追求的解决方案之一:

f <- function(x,y){
  a <- NULL
  for (i in 1:x){
    a[i] <- choose(x,i) - choose(x-y,i-y)}
  return(sum(a))}
f(5,2)

@Andrew Gustar - 感谢您的建议!

我仍然需要为要排除变量的矩阵找到更通用的解决方案(其中一些是不同的,其中一些不是):

vector <- c("var1","var2","var3","var4","var5","var6","var7","var8")
exclude <- matrix(c(c("var3","var2"),c("var4","var3"),c("var5","var7")),3,2)).
于 2017-08-05T17:56:05.247 回答