Reputation: 502
I have a vector and need to find all combinations where the sum is between a range.
set.seed(007)
w <- round(runif(10, 0, 1) * 100)
w
[1] 99 40 12 7 24 79 34 97 17 46
I want a matrix of all combinations (without repetition) of these numbers in "w" whose sum is between 50 and 55 The matrix can contain values 0 and 1 whether the value at that position is to be considered in that solution
Eg: 0 1 1 0 0 0 0 0 0 0 means 40 and 12 are to be considered
There are many solutions available but they are using repetitions. I couldnt make out how to do this in R.
Any ideas.
Upvotes: 0
Views: 190
Reputation: 13159
We can use combn
, it creates combinations from a vector, without repetitions.
First, we create all combinations:
w_comb <- combn(w,2)
Then we test wether our combinations fullfill our constraints. We do this (thanks nicola) with colSums.
w_comb_tests <- colSums(w_comb) >= 50 & colSums(w_comb) <= 55
Finally, we generate a row of 0s and 1s for each selected combination:
res <- t(apply(w_comb[,w_comb_tests],2,function(x){
as.numeric(w %in% x)
}))
Upvotes: 3