如何在R中的for循环中使用tryCatch

时间:2014-02-06 15:45:36

标签: r for-loop try-catch

我正在尝试估算R中for循环中的很多模型。我首先为变量'Date'定义了一组可能的值,并将它们存储在'Dates'中。然后,对于每个模型,我根据“日期”的这些值定义一般数据集的子集。

最终,我的目标是将所有这些模型的一些系数存储在两个矩阵中:effRain和effWindchill。

问题是:在某些情况下,由于错误,无法估算glmer模型。在这些情况下,我希望循环跳过并继续循环中的下一步。但是,我对R不是很有经验。我发现我可能需要使用tryCatch,但我应该如何将其融入我的代码中呢?我一直在努力尝试,但我无法理解。

到目前为止,这是我的代码:

Dates <- c(19710428,19721129,19740529,19770525,19780531,19810526,19820602,19820908,
19840614,19860319,19860521,19890615,19890906,19900321,19940302,19940503,
19940609,19980304,19980506,19990303,19990610,20020206,20020515,20030122,
20030311,20040610,20060307,20061122,20070307,20090604,20100303,20100609,
20110302,20120912)

effRain <- matrix(nrow=34,ncol=2,0)
effWindchill <- matrix(nrow=34,ncol=2,0)

for(i in 1:34){
hulpdata <- hulpdata <- subset(banaan,Date==Dates[i])
attach(hulpdata)
SP2 <- SP/100
model1 <- glmer (cbind(opkomst, nnietgestemd) ~
       (1|gemnr)+ Windchill + Rain + Windspeed + SP2 + lag_popkomst + NB + OL + loginw 
       , family=binomial(link=logit))
effRain[i] <- coef(summary(model1))[3]
effWindchill[i] <- coef(summary(model1))[2]
}

1 个答案:

答案 0 :(得分:1)

我建议不要在此处使用for并使用lapply来避免for副作用并预先分配结构结果内存。

代码应该是这样的

 lapply(Dates,estimat_coef)

模型代码封装在如下所示的函数中。我只是将您的代码放入(tryCatcherror)。

estimat_coef <-
  function(x){
    res = tryCatch({
      hulpdata <- hulpdata <- subset(banaan,Date==x)
      attach(hulpdata)
      SP2 <- SP/100
      model1 <- glmer (cbind(opkomst, nnietgestemd) ~
                         (1|gemnr)+ Windchill + Rain + Windspeed + SP2 + 
                         lag_popkomst + NB + OL + loginw 
                       , family=binomial(link=logit))
      list(effRain =coef(summary(model1))[3],  
           effWindchill = coef(summary(model1))[2])
    },error=function(e)list(effRain=NA,effWindchill=NA))
    res
  }