Catch an error by producing NA

2019-04-26 05:04发布

问题:

I wish to get NA when a function returns an Error rather than the code halting.

I currently use

try.test<-try(results<-lm(log(0)~1))
if(class(try.test)=="try-error"){results<-NA}

I also tried playing with tryCatch.

I would like to find a single function/line solution.

回答1:

Try

result <- tryCatch(lm(log(0)~1), error=function(err) NA)

But this catches all errors, not just those from log(0).



回答2:

A less than classy, but equally short way of solving your problem.

results <- NA
try(results<-lm(log(0)~1), silent = TRUE)

If you're looking for an elegant way to handle errors, I recommend looking into the concept of a monad; using these structures reduces the amount of "if(!na(x))...." boilerplate in your scripts.