Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does R say no loop for break/next, jumping to top level

Tags:

r

Why does R throw the error "Error in value[3L] : no loop for break/next, jumping to top level" instead of going to the next iteration of a loop? I'm on R version 2.13.1 (2011-07-08)

for (i in seq(10)) { 
   tryCatch(stop(), finally=print('whoops'), error=function(e) next) 
}

This problem came up because I wanted to create a different image or no image at all when plot failed. The code, using joran's approach, would look like this:

for (i in c(1,2,Inf)) { 
   fname = paste(sep='', 'f', i, '.png')
   png(fname, width=1024, height=768) 
   rs <- tryCatch(plot(i), error=function(e) NULL)
   if (is.null(rs)){
    print("I'll create a different picture because of the error.")
   }
   else{
    print(paste('image', fname, 'created'))
    dev.off()
    next
   } 
}
like image 283
selden Avatar asked Aug 11 '11 22:08

selden


2 Answers

Maybe you could try :

for (i in seq(10)) { 
   flag <- TRUE
   tryCatch(stop(), finally=print('whoops'), error=function(e) flag<<-FALSE)
   if (!flag) next
}
like image 195
Simon Avatar answered Sep 16 '22 14:09

Simon


Unfortunately, once you get inside your error function you're no longer in a loop. There's a way you could hack around this:

for (i in seq(10)) { 
   delayedAssign("do.next", {next})
   tryCatch(stop(), finally=print('whoops'),
        error=function(e) force(do.next))
}

Though that is... well, hacky. Perhaps there is a less hacky way, but I don't see one right off.

(This works because delayedAssign happens every loop, canceling out the efforts of force)

EDIT

Or you could use continuations:

for (i in seq(10)) { 
   callCC(function(do.next) {
       tryCatch(stop(), finally=print('whoops'),
           error=function(e)    do.next(NULL))
       # Rest of loop goes here
       print("Rest of loop")
   })
}

EDIT

As Joris points out, you probably shouldn't actually use either of these, because they're confusing to read. But if you really want to call next in a loop, this is how :).

like image 27
Owen Avatar answered Sep 20 '22 14:09

Owen