# [R] problem with break command

Berend Hasselman bhh at xs4all.nl
Thu Apr 26 21:39:12 CEST 2012

```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

```