Continuing a ‘for’ loop in R after an error


Lately, I’ve been using loops to fit a number of different models and storing the models (or their predictions) in a list (or matrix)–for instance, when bootstrapping. The problem I was running into was the for loop screeching to a halt as soon as a model kicked back an error. I wanted the function to register an error for that entry, then skip to the next one and finish off the loop.

Luckily, there’s a function called next that does just that. But I found it difficult to get the function to work, even after consulting the help file, and from searching R listservs/Stackoverflow. So I’ve provided some example code here to help those who are facing the same issue.

For the example, I fit a linear mixed effects model using lmer (just because I happen to be working with mixed models, and they throw back convergence errors more often than GLMs), then used the update function to challenge it with random draws from my dataframe. I stored the models in a list, but you could just as easily create a dummy matrix and store predictions using the predict function within the loop.

#Load nlme

#Create data frame

#Build model

#Create random draws from data frame to update model using a loop
df2=df; df2$y=1 #Create bunk dataframe to throw back an error

#Create list to store updated models
#Update models using for loop and store in the list
for(i in seq_along(df.list)) {
  if(isTRUE(class(mod2)=="try-error")) { next } else { mod.list[i]=mod2 } }

There has been some blow back against for loops, so an alternative is using lapply and writing a function to update the models:

#Update models using lapply and store in a list
mod.list=lapply(seq_along(df.list),function(i) {
  if(isTRUE(class(mod2)=="try-error")) { return(NULL) } else { return(mod2) } } )

It’s a little harder to get predictions to a matrix using lapply. In this case, you could use predict within the function, then pass the list to,mod.list).

Created by Pretty R at

Image credit:

4 thoughts on “Continuing a ‘for’ loop in R after an error

  1. nickmason000 says:

    I had recently come upon the same solution. In your post the emphasis seems to be on the ‘next’ function, when in my opinion ‘try’ is really the workhorse here. You could remove ‘next’ and just have empty brackets if a try-error is not encountered and you’ll get the same result.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s