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.
Try
result <- tryCatch(lm(log(0)~1), error=function(err) NA)
But this catches all errors, not just those from log(0).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With