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!

### Like this:

Like Loading...