How to ignore an error in R?

Asked

Viewed 212 times

2

I created a function inside, however, if at some point an error occurs, it is not important to me and I want it to continue until the end, ignoring the error.

valor<-1
Erro<-function(valor){
  valor<-valor+1
  print(valor)
  valor<-valor+1
  print(valor)
  na.fail(NA)
  valor<-valor+1
  print(valor)
  valor<-valor+1
  print(valor)
}
Erro(valor)

And what repercussions of that?

  • I don’t know if this is what you want: tryCatch(na.fail(NA), error = function(e) print(e)).

1 answer

3


There are several ways to process errors available in R, perhaps the most frequently used is the function tryCatch.

Erro <- function(valor){
  valor <- valor + 1
  print(valor)
  valor <- valor + 1
  print(valor)
  err <- tryCatch(na.fail(NA), error = function(e) e)
  if(inherits(err, "error")) print(err)
  valor <- valor + 1
  print(valor)
  valor <- valor + 1
  print(valor)
}

valor <- 1
Erro(valor)
#[1] 2
#[1] 3
#<simpleError in na.fail.default(NA): missing values in object>
#[1] 4
#[1] 5

Another good reference is the Advanced R of Hadley Wickham.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.