通过产生NA来捕获错误

时间:2021-06-14 20:21:52

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

我希望在函数返回错误而不是代码暂停时获得NA。

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.

我也尝试过使用tryCatch。

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

我想找到一个功能/线路解决方案。

2 个解决方案

#1


15  

Try

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

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

但这会捕获所有错误,而不仅仅是log(0)中的错误。

#2


4  

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.

如果你正在寻找一种处理错误的优雅方法,我建议你研究monad的概念;使用这些结构可以减少脚本中“if(!na(x))....”样板的数量。

#1


15  

Try

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

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

但这会捕获所有错误,而不仅仅是log(0)中的错误。

#2


4  

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.

如果你正在寻找一种处理错误的优雅方法,我建议你研究monad的概念;使用这些结构可以减少脚本中“if(!na(x))....”样板的数量。

相关文章