Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch an error by producing NA

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.

like image 429
Etienne Low-Décarie Avatar asked Feb 03 '13 02:02

Etienne Low-Décarie


2 Answers

Try

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

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

like image 167
Martin Morgan Avatar answered Sep 30 '22 06:09

Martin Morgan


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.

like image 39
Róisín Grannell Avatar answered Sep 30 '22 05:09

Róisín Grannell