Thanks Berend, you are right. The break command would not work here. But the while loop is taking time to generate the desired.
On Thu, Apr 26, 2012 at 2:39 PM, Berend Hasselman <b...@xs4all.nl> wrote: > > On 26-04-2012, at 21:30, cassie jones wrote: > > > Hello R-users, > > > > I am having a problem with the 'break' command in R. I am wondering if > > anyone can help me out with this. My program is similar to the following. > > > > a=rep(NA,5) > > a[1]=0 > > for(i in 2:5) > > { > > a[i]=a[i-1]+runif(1,0,3) > > if(a[i]>5) > > { > > i=2 > > break > > } > > } > > > > What exactly I am trying to do is find the sequence 'a' where the > > individual values of 'a' would not be larger than 5. In any sequence, if > it > > becomes larger than 5, it would set the counter to be 2 and regenerate > from > > i=2. But I guess I have not put the break command in the right place, so > > even though the 'if' condition becomes true and it sets i=2, it does not > > regenerate the values of 'a' since the beginning. Any help is really > > appreciated. > > > break will exit the for loop. You cannot achieve what you desire with > break. > > You need a while loop for this. > > i <- 2 > while( i <= 5 ) > # for(i in 2:5) > { > a[i] <- a[i-1]+runif(1,0,3) > if(a[i]>5) i <- 2 else i <- i+1 > } > > And hope that the while loop will eventually terminate. > > Berend > > [[alternative HTML version deleted]] ______________________________________________ R-help@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.