Handling Errors Gracefully

May 27, 2011
By

(This article was first published on Software for Exploratory Data Analysis and Statistical Modelling, and kindly contributed to R-bloggers)

In R functions sometimes produces warnings or errors. In the case of errors execution of a function or a series of commands can get halted when an error occurs, which can in some cases be frustrating especially if we want to continue our calculations.

There are various functions available in R for dealing with errors and in this post we will consider some basic examples of how to make use of the try function.

To illustrate how to use try let’s look at what happens if we run code to print out a non-existent object in our workspace:

> print(d)
Error in print(d) : object 'd' not found

Now if we try to run another command at the same time to print out a string then we would get the following output:

> print(d); print("Hi")
Error in print(d) : object 'd' not found

Here execution of the code halts after the first command fails and generates an error. We can modify this code to call the try function with the print statement:

> try(print(d)); print("Hi")
Error in print(d) : object 'd' not found
[1] "Hi"

The second statement is now evaluated even though an error occurs at the first statement. This is a trivial example and in other situations we might consider using the tryCatch function which has various arguments in addition to the expression to evaluate including a function to be called when an error occurs.

To leave a comment for the author, please follow the link and comment on his blog: Software for Exploratory Data Analysis and Statistical Modelling.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Tags: , , ,

Comments are closed.