1

I'm not really understanding how tryCatch works. Especially the last part where you store your error message. There are a lot of posts on Stackoverflow about how to use tryCatch, but the solutions generally just post an error message and then move on. I'd like to store the indices of the for loop where the errors occurred so I can go back to them easily later. I'm thinking about something as follows using tryCatch

  flag = NULL

    for(i in 1:10) { 
      do something that can cause an error
      if (error occurs) flag=c(flag,i) and move on to the next iteration
    }

Ideally I'd like flag to store the indices during the errors.

WetlabStudent
  • 2,556
  • 3
  • 25
  • 39

1 Answers1

3

You might have to use <<- to assign to the parent environment, although this is probably considered poor practice. For example:

a <- as.list(1:3)
flag <- integer()
for (i in 1L:5L){
  tryCatch(
    {
      print(a[[i]])
    },
    error=function(err){
      message('On iteration ',i, ' there was an error: ',err)
      flag <<-c(flag,i)
    }
  )
}
print(flag)

Returns:

[1] 1
[1] 2
[1] 3
On iteration 4 there was an error: Error in a[[i]]: subscript out of bounds

On iteration 5 there was an error: Error in a[[i]]: subscript out of bounds

> print(flag)
[1] 4 5

Does that help?

C8H10N4O2
  • 18,312
  • 8
  • 98
  • 134
  • Not too poor practice; Luke Tierney recommended a version of this on the R-help mailing list once. See https://stackoverflow.com/a/4947528/210673 for his code, which collects warnings, and https://stackoverflow.com/q/4948361/210673 for a version that collects errors too. – Aaron left Stack Overflow Oct 08 '19 at 02:22