13.3.4 Tracking with the trace() Function.................................
Thetrace()function is flexible and powerful, though it takes some initial
effort to learn. We will discuss some of the simpler usage forms here, begin-
ning with the following:
trace(f,t)
This call instructs R to call the functiont()every time we enter the func-
tionf(). For instance, say we wish to set a breakpoint at the beginning of the
functiongy(). We could use this command:
trace(gy,browser)
This has the same effect as placing the commandbrowser()in our source
code forgy(), but it’s quicker and more convenient than inserting such a
line, saving the file, and rerunningsource()to load in the new version of the
file. Callingtrace()doesnotchange your source file, though it does change
a temporary version of your file maintained by R. It would also be quicker
and more convenient to undo, by simply runninguntrace:
untrace(gy)
You can turn tracing on or off globally by callingtracingState(), using
the argumentTRUEto turn it on orFALSEto turn it off.
13.3.5 Performing Checks After a Crash with the traceback() and
debugger() Functions
Say your R code crashes when you are not running the debugger. There
is still a debugging tool available to you after the fact. You can do a “post-
mortem” by simply callingtraceback(). It will tell you in which function the
problem occurred and the call chain that led to that function.
You can get a lot more information if you set up R to dump frames in
the event of a crash:
options(error=dump.frames)
If you’ve done this, then after a crash, run this command:
debugger()
You will then be presented with a choice of levels of function calls to
view. For each one that you choose, you can take a look at the values of the
variables there. After browsing through one level, you can return to the
debugger()main menu by hitting N.
Debugging 291