Dongdong Kong
Dongdong Kong

Reputation: 416

R foreach stop iteration at i

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)
    }
}

Upvotes: 0

Views: 322

Answers (1)

Ian Wesley
Ian Wesley

Reputation: 3624

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

Upvotes: 1

Related Questions