I have an input vector such as:
weights <- seq(0, 1, by = 0.2)
I would like to generate all the combinations of weights (repeats allowed) such that the sum is equal to 1.
I came up with
l <- rep(list(weights), 10)
combinations <- expand.grid(l)
combinations[which(apply(combinations, 1, sum) == 1),]
The problem is of course I generate far more combinations that I need. Is there a way to get it done more efficiently?
EDIT:
Thanks for the answers. That's the first part of the problem. As @Frank pointed out, now that I have all the "solutions" that add up to 1, the problem is to get all the permutations (not sure if it is the right word) from the solutions in a vector of length 10. For instance:
s1 <- c(0, 0, 0.2, 0, 0, 0, 0.8, 0, 0, 0)
s2 <- c(0.8, 0, 0, 0, 0, 0, 0, 0, 0.2, 0)
etc...
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…