Problem

You want to debug a script or function.

Solution

Insert this into your code at the place where you want to start debugging:

browser()

When the R interpreter reaches that line, it will pause your code and you will be able to look at and change variables.

In the browser, typing these letters will do things:

   
c Continue
n (or Return) Next step
Q quit
Ctrl-C go to top level

When in the browser, you can see what variables are in the current scope.

ls()

To pause and start a browser for every line in your function:

debug(myfunction)
myfunction(x)

Useful options

By default, every time you press Enter at the browser prompt, it runs the next step. This is equivalent to pressing n and then Enter. This can be annoying. To disable it use:

options(browserNLdisabled=TRUE)

To start debugging whenever an error is thrown, run this before your function which throws an error:

options(error=recover)

If you want these options to be set every time you start R, you can put them in your ~/.Rprofile file.