Fixing broken loops with tryCatch() in R

Say you are using a loop that calls a function at each iteration. What happens if that function returns a error part way through the process? Your loop wont complete even if some suitable data remains!

One solution is the tryCatch() function in R. It can be used to first ‘try’ the loop and upon encountering an error it will call a predetermined function. This allows your loop to complete.

Below is a (silly) example but illustrates the idea.

Say we want to generate a vector of correlations:

# generating columns
x = rnorm(4)
y = rnorm(4)
z = rnorm(4)
q = rnorm(4)

# forming a data frame
data = data.frame(cbind(x,y,z,q))

# lets make the 'z' column a collection of character values!
data$z = as.character(data$z)

# viewing
str(data)

# creating an empty vector
correlations = rep(0,length(data))

# trying to run a loop
for(i in 1:length(data)){
  correlations[i] = cor(data$x,data[,i])}

# oops!!! We have an error!!!
correlations

# using tryCatch()
# the function will try the expression first. When this fails, 0 will be returned.
for(i in 1:length(data)){
  correlations[i] = tryCatch({expr=cor(data$x,data[,i])},
                             error=function(i){return(NA)})
}

# result!
correlations

Hope this helps!

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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