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. Thanks in advance. Cassie [[alternative HTML version deleted]]
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
On Thu, Apr 26, 2012 at 02:30:09PM -0500, 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 > } > }Hi. Berend sent you a solution. Perhaps, one thing concerning the for loops in R should be clarified. The variable specified as the loop variable is not the true loop variable, which controls the loop, since one can have a loop for (i in c(1, 1, 1, 1, 1)). The true control variable is hidden and cannot be changed. So the for loop for (i in 1:3) { for (i in 1:4) { cat("*") } cat("\n") } works correctly although the visible loop variables are the same. Petr Savicky.