0

I have a nested for loop that needs to be able to skip to the next iteration in the event of an error. The error is happening in the inner most loop.

I tried using try_catch, but I'm met with an error. How should I approach this? Maybe my logic for the for loop is not correctly aligned with try_catch.

Here is my attempt at trying to skip to the next iteration in the inner most loop.

df <- data.frame(
  name = c("Neo","Mr.Smith","Morpheus"),
  age = c(22,'2',28)
)

youth <- df$age

for(i in df$name){

  for (j in youth){
## error handler
    tryCatch({
# error here
      if(!is.numeric(j)) {
        stop("Not numeric", j)
    } else {
      print(j)
    }
  }, error = function(e) {
  next
  })
}
  print(i)
}
  • 1
    Your example is not great - a vector can only have one class, so when you define `age = c(22,'2',28)` then `age` is `character` class. The whole vector, every element. Maybe use a numeric `age = c(22, 2, 28)` and test `if(j < 20)` for the error. – Gregor Thomas Jun 13 '23 at 16:18
  • 1
    This seems very well explained at the marked dupliate - Andrie's answer gives great detail, stevec's answer gets right to a solution, and OP (isomorphismes) provides a nice conceptual summary in their answer. If you read through those and still need help, I'd suggest opening a new question focused on your specifics. – Gregor Thomas Jun 13 '23 at 16:25
  • @GregorThomas thanks Gregor! it took me a while to play with, but the post you mentioned helped a lot – wigglesthe3rd Jun 13 '23 at 17:20

0 Answers0