Debugging in R

August 30, 2007

(This article was first published on Research tips » R, and kindly contributed to R-bloggers)

Anyone who starts writing serious R code (i.e., code that involves user-written functions) soon finds the need to use debugging tools. There are a few basic tools in R that are worth knowing about.

The function debug() allows one to step through the execution of a function, line by line. At any point, you can print out values of variables or produce a graph of the results within the function. While debugging, you can simply type “c” to continue to the end of the current section of code (e.g., to the end of a for loop, or the end of the function itself).

The function browser() stops the execution of a function until the user allows it to continue. This is useful if you don’t want to step through all the code, line-by-line, but you want it to stop at a certain point so you can check out what is going on.

If your code has already crashed and you want to know where the offending line is, try traceback(). This will (sometimes) show where abouts in the code the problem occurred.

Check out the help files for the above functions for the details.

Duncan Murdoch also has an excellent debugging page on the web: Debugging in R which contains a wealth of extremely helpful information.

To leave a comment for the author, please follow the link and comment on his blog: Research tips » R. 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.