I am trying to figure out how to reckon the number of combinations returned by combn function after exclusion of some selected combinations. Let's say, we have a vector c("var1","var2","var3","var4","var5") and I want to get all combinations of the elements of this one except these that consits of c("var4","var5"). Here is the code:
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)}}
}
The number of combinations returned from combn function without any reduction is 31. It is reckoned as:
f <- function(nvars){
a <- NULL
for (i in 1:nvars){
a[i] <- choose(nvars,i)}
return(sum(a))}
f(5)
Any suggestions how to get the number of reduced combinations (for 5 variables and exclusion of combinations that contain "var4" and "var5" at same time, it should be 23). Thanks!
答案 0 :(得分: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
答案 1 :(得分:-1)
We loop through the sequence of vector
, get the combn
by specifying the 'm' as the sequence value, then check whether all
the 'exclude' elements are there %in%
the combination elements, negate (!
), unlist
the list
and get the sum
of logical elements
sum(unlist(lapply(seq_along(vector), function(i) combn(vector, i,
FUN = function(x) !all(c(exclude) %in% x)))))
#[1] 23
答案 2 :(得分:-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)).