[R] Speeding up a loop
wwreith
reith_william at bah.com
Fri Jul 20 14:45:30 CEST 2012
General problem: I have 20 projects that can be invested in and I need to
decide which combinations meet a certain set of standards. The total
possible combinations comes out to 2^20. However I know for a fact that the
number of projects must be greater than 5 and less than 13. So far the the
code below is the best I can come up with for iteratively creating a set to
check against my set of standards.
Code
x<-matrix(0,nrow=1,ncol=20)
for(i in 1:2^20)
{
x[1]<-x[1]+1
for(j in 1:20)
{
if(x[j]>1)
{
x[j]=0
if(j<20)
{
x[j+1]=x[j+1]+1
}
}
}
if(sum(x)>5 && sum(x)<13)
{
# insert criteria here.
}
}
my code forces me to create all 2^20 x's and then use an if statement to
decide if x is within my range of projects. Is there a faster way to
increment x. Any ideas on how to kill the for loop so that it won't attempt
to process an x where the sum is greater than 12 or less than 6?
--
View this message in context: http://r.789695.n4.nabble.com/Speeding-up-a-loop-tp4637201.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list