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!
This will calculate the number of combinations for any input vector
and exclude
(it is based on your loop in the question)...
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