breaking out of for loop when running a function inside a for loop

Posted by andrewj on Stack Overflow See other posts from Stack Overflow or by andrewj
Published on 2010-03-25T04:52:05Z Indexed on 2010/03/25 5:13 UTC
Read the original article Hit count: 622

Filed under:
|

I'm embarrassed that I'm asking this question, but here I go:

Suppose you have the following function foo. When I'm running a for loop, I'd like it to skip the remainder of foo when foo initially returns the value of 0. However, break doesn't work when it's inside a function.

As it's currently written, I get an error message, no loop to break from, jumping to top level.

Any suggestions?

foo <- function(x) {
    y <- x-2
    if (y==0) {break} # how do I tell the for loop to skip this
    z <- y + 100
    z
}


for (i in 1:3) {
    print(foo(i))
}

© Stack Overflow or respective owner

Related posts about r

    Related posts about for-loop