R foreach stop iteration at i

310 Views Asked by At

I am using R package foreach. When bug exists in foreach block, it's hard to re-occur it and hard to debug.

Take the following script as example. I want to stop at i=4 to check what's wrong. However, it stops at i=10.

Any solution?

library(foreach)
foreach(i = icount(10)) %do% {
    if (i == 4){
        e <- simpleError("test error")
        stop(e)
    }
}
1

There are 1 best solutions below

0
On

One option to handle this is with a browser() inside a tryCatch as in:

foreach(i = icount(10)) %do% {
  tryCatch(
    if (i == 4){
      e <- simpleError("test error")
      stop(e)
    },
    error = function(e) browser()
  )
}

This will produce a browser of the environment at the time of the error, which will allow you to inspect any objects and/or debug your code.

Your console will then look like the following and you can ask what the value of i is. Like this:

Browse[1]> i

[1] 4