How to ignore an error in R?

2

I created a function inside, however, if at some point an error occurs, it's not important to me and I want it to go through to 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 are the repercussions of this?

    
asked by anonymous 27.10.2018 / 18:25

1 answer

3

There are several ways to handle errors available in R, perhaps the most frequently used is the 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 Hadley Wickham's Advanced R .

    
02.11.2018 / 09:20