如何忽略错误并继续处理列表项? [英] How do I ignore errors and continue processing list items?

查看:104
本文介绍了如何忽略错误并继续处理列表项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用包装函数通过 glm.nb 运行几百个数据集。没有什么花哨,我只需通过 llply 传递每个列表项,然后使用 glm.nb 将系数写入一个 data.frame 并返回。



毫不奇怪,glm.nb无法收敛某些数据集。而不是让功能咳嗽一个错误并停止,我宁愿继续通过其余的数据集,并在可能的情况下返回结果。



我的第一次尝试是这个:

  res.model<  -  function(x)
{
res< - try (invisible(glm.nb(x〜y,data = x)))
if(!(try-error%in%class(res)))
{
return data.frame(site = unique(x $ site_name),species = unique(x $ species),coef = res $ coefficients [2]))
}
}
解决方案

我有一个nls(),我运行有同样的挑战。我正在对数据框架中的每一个组进行回归,但这个逻辑也适用于你(我认为):

  dlply(myData,c(group1,group2),function(df){
tryCatch(nls(depen〜exp(a1 + b1 * year)),data = df,start = list a1 = -1,b1 = 0),na.action = na.omit),error = function(e)NULL)

所以如果我想猜测如何应用于你的情况,那将是这样的:

  res<  -  trycatch(glm.nb(x〜y,data = x),error = function(e)NULL)

我使用这种方式,我在任何时候回归不会收敛时抛出NA值,你可能想做一些不同的事情。


I'm running several hundred datasets through glm.nb using a wrapper function. Nothing fancy, I just pass on each list item via llply, then fit using glm.nb, write the coefficients to a data.frame and return that back.

Not surprisingly, glm.nb fails to converge for some datasets. Rather than have the function cough up an error and stop, I'd prefer that it continue through the rest of the datasets and return results where possible.

My first attempt was this:

res.model <- function(x)
       {
       res <- try(invisible(glm.nb(x~y, data=x)))
   if(!("try-error" %in% class(res)))
       {
    return (data.frame(site=unique(x$site_name),species=unique(x$species),coef=res$coefficients[2]))
       }
 }

Any thoughts on a more generic way to ignore errors so I can make this work?

解决方案

I have an nls() which I run that has the same challenge. I'm applying the regression to every group in a data.frame, but this logic should work for you as well (I think):

 dlply(myData, c("group1", "group2"), function(df){  
       tryCatch(nls(depen ~ exp(a1 + b1 * year) , data=df, start = list(a1 = -1, b1 = 0), na.action=na.omit), error=function(e) NULL)

so if I were to guess how to apply that to your situation, it would be something like:

res <- trycatch(glm.nb(x~y, data=x), error=function(e) NULL )

The way I use this, I'm throwing NA values any time the regression does not converge. You may want to do something different.

这篇关于如何忽略错误并继续处理列表项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆