Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

for-loop

r

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))
}
like image 519
andrewj Avatar asked Mar 25 '10 04:03

andrewj


2 Answers

Admittedly my R knowledge is sparse and this is drycoded, but something like the following should work:

foo <- function(x) {
    y <- x-2
    if (y==0) {return(NULL)} # return NULL then check for it
    z <- y + 100
    z
}

for (i in 1:3) {
    j <- foo(i)
    if(is.null(j)) {break}
    print(j)
}

Edit: updated null check for posterity

like image 88
Dusty Avatar answered Oct 24 '22 18:10

Dusty


As a matter of coding practice, don't do this. Having a function that can only be used inside a particular loop is not a great idea. As a matter of educational interest, you can evaluate the 'break' in the parent environment.

foo <- function(x) {
    y <- x-2
    if (y==0) {eval.parent(parse(text="break"),1)} 
    z <- y + 100
    z
}



for (i in 0:3) {
    print(foo(i))
}
like image 30
Ian Fellows Avatar answered Oct 24 '22 16:10

Ian Fellows