Debugging in R

There are several utilities for debugging in R.

Debugging with traceback()

Whenever a custom function generates an error, the traceback() function is a good way to focus initial problem solving.  The function lists the nested function calls currently being evaluated, starting with the function from which the error was returned and working outward to the original calling function.

Printing Intermediate Results

One of the oldest techniques for debugging, and still widely used, is to print intermediate results of computations using strategically placed cat(), print() and show() statements.  In general, the cat() function prints the output in the simplest form possible, while the latter two produce output that is class specific.

The example below recycles the iterative function silly.csum() with a calls to cat() and print() at the end of the for() loop.  We can now examine incremental calculations as the loop iterates:

Debugging with browser()

The browser() and browser.default() functions are useful for debugging functions when you know an error occurs after some point in the function. If you insert a call to browser() into your function at that point, you can check all assignments up to that point, and verify that they are indeed the correct ones. browser() can be used to try out revisions in real time, without exiting or editing the function.  Typing stop or q terminates the browser() function.

The example below again uses silly.csum() with a call to browser() inserted at the end of the for() loop.  browser() pauses the function run to allow interactive use of the Console.  Hitting enter allows the function to continue until the next browser pause.  Again, we examine incremental calculations as the loop iterates:

Back | Next

Leave a Reply