can this sequence be generated easier?
Here ia an idea that might be useful to adapt
fixedSumCombinations <- function(N, terms)
if(terms == 1) return(N) else
if(terms == 2) return(cbind(0:N, N:0)) else {
X <- NULL
for(i in 0:N)
X <- rbind(X, cbind(i, Recall(N-i, terms-1)))
X
}
example:
fixedSumCombinations(4, 3)
i [1,] 0 0 4 [2,] 0 1 3 [3,] 0 2 2 [4,] 0 3 1 [5,] 0 4 0 [6,] 1 0 3 [7,] 1 1 2 [8,] 1 2 1 [9,] 1 3 0 [10,] 2 0 2 [11,] 2 1 1 [12,] 2 2 0 [13,] 3 0 1 [14,] 3 1 0 [15,] 4 0 0 Bill Venables.
From: r-help-bounces at r-project.org [r-help-bounces at r-project.org] On Behalf Of pdb [philb at philbrierley.com]
Sent: 18 June 2011 14:34
To: r-help at r-project.org
Subject: [R] can this sequence be generated easier?
Sent: 18 June 2011 14:34
To: r-help at r-project.org
Subject: [R] can this sequence be generated easier?
I have 'x' variables that I need to find the optimum combination of, with the
constraint that the sum of all x variables needs to be exactly 100. I need
to test all combinations to get the optimal mix.
This is easy if I know how many variables I have - I can hard code as below.
But what if I don't know the number of variables and want this to be a
flexible parameter. Is there a sexy recursive way that this can be done in
R?
#for combinations of 2 variables
vars = 2
for(i in 0:100){
for(j in 0:(100-i)){
...do some test i,j combination
}}
#for combinations of 3 variables
vars = 3
for(i in 0:100){
for(j in 0:(100-i)){
for(k in 0:100-(i+j)){
...do some test on i,j,k combination
}}}
--
View this message in context: http://r.789695.n4.nabble.com/can-this-sequence-be-generated-easier-tp3607240p3607240.html
Sent from the R help mailing list archive at Nabble.com.
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.