pm-b
pm-b

Reputation: 158

How to use tryCatch in a for-loop in R

I'm trying to estimate a lot of models in a for-loop in R. I first defined a set of possible values for the variable 'Date', and stored these in 'Dates'. Then, for each model, I define a subset of a general dataset, according to these values of 'Dates'.

Eventually, my aim is to store some coefficients of all these models in two matrices: effRain and effWindchill.

The problem is: in some instances, the glmer model cannot be estimated, due to an error. In these cases, I want the loop to skip and continue to the next step in the loop. However, I'm not very experienced in R. I found out I probably need to use tryCatch, but how should I fit this into my code? I've been trying and trying, but I just can't figure it out.

This is my code up till now:

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]
}

Upvotes: 1

Views: 1764

Answers (1)

agstudy
agstudy

Reputation: 121568

I recommend not using for here and use lapply to avoid for side effect and pre-allocating structures results memory.

The code should something like this

 lapply(Dates,estimat_coef)

Where the model code is encapsulated within a function like this one below. I just put your code within (tryCatch,error).

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
  }

Upvotes: 1

Related Questions