R Programming/Debugging

Some basic tips

 * Use  statements in your functions to print variable values. Although this technique is considered low-tech or even old fashioned by some, it can still be a quick and easy way to trace an error.
 * Place a  statement in the function just before the crashing line. When the function is called, it will be executed up to the   line. The command-line interface then switches to the function environment, so that all variables in the function can be inspected or changed.  See below for commands available in   mode.

Tracing errors with
A standard error message in R will tell you which function threw the error. Consider as an example the following function whose sole purpose is to throw an error. A call to  gives

After an error is raised, the  function allows you to show the call stack leading to the error. For example, the function below calls.

Calling  and   gives

The  function can be executed automatically each time an error is raised with the option

It may be switched off again with

Executing code line by line
A function can be executed by setting it to debugging mode with . Then, when the function is called, and a browser in that function's environment is opened so that it can be executed line by line. In the debugging browser, apart from all standard R functionality, the following commands are available.

Debugging can be switched off with

There are a few related functions as well:
 * Switch off debugging after the first call.
 * Check if a function is in degugging mode.

Browsing the call stack
This is the most advanced debugging option in R base. By setting you get the opportunity to browse any environment in the call stack. For example, By typing '1' or '2' behind  the browser will jump to the selected environment. Once in the browser, all standard R functionality is at your disposal, as well as the commands in the table below.

Recovery mode can be switched off by