13.3.2 Using Browser Commands.......................................
While you are in the browser, the prompt changes from>toBrowse[d]>.
(Here,dis the depth of the call chain.) You may submit any of the following
commands at that prompt:
- n(fornext): Tells R to execute the next line and then pause again. Hit-
tingENTERcauses this action, too. - c(forcontinue): This is liken, except that several lines of code may be
executed before the next pause. If you are currently in a loop, this com-
mand will result in the remainder of the loop being executed and then
pausing upon exit from the loop. If you are in a function but not in a
loop, the remainder of the function will be executed before the next
pause. - Any R command: While in the browser, you are still in R’s interactive
mode and thus can query the value of, say,xby simply typingx.Of
course, if you have a variable with the same name as a browser com-
mand, you must explicitly call something likeprint(),asinprint(n). - where: This prints astack trace. It displays what sequence of function calls
led execution to the current location. - Q: This quits the browser, bringing you back to R’s main interactive mode.
13.3.3 Setting Breakpoints.............................................
Callingdebug(f)places a call tobrowser()at the beginning off(). However,
this may be too coarse a tool in some cases. If you suspect that the bug is in
the middle of the function, it’s wasteful to trudge through all the interven-
ing code.
The solution is to setbreakpointsat certain key locations of your code—
places where you want execution to be paused. How can this be done in R?
You can callbrowserdirectly or use thesetBreakpoint()function (with R ver-
sion 2.10 and later).
13.3.3.1 Calling browser() Directly
You can set a breakpoint by simply inserting calls tobrowser()at the places of
interest in your code. This has the effect, essentially, of setting breakpoints
there.
You can make invoking the browser conditional so that it is entered only
in specified situations. Use theexprargument to define those situations. For
instance, suppose you suspect that your bug arises only when a certain vari-
ablesis larger than 1. You could use this code:
browser(s > 1)
Debugging 289