Debugging
Architect has an advanced tool for visual debugging. In this exercise, we’ll use the following code to demonstrate the debugging functionality:
myFun <- function(x){
y <- x + 2
z <- y - 3
myOtherFun(z)
}
myOtherFun <- function(x) {
m <- matrix(diag(x), ncol = 2)
colnames(m) <- c("A", "B")
return(m)
}
data(cars)
# myFun(6)
Launch via debugger icon
The visual debugger can only be used within an R session launched by the Debugger icon () in the top toolbar. Click on the icon and select the R version you’d like to use.
Set a breakpoint
Visual debugging works with the concept of breakpoints. By setting a breakpoint, you instruct Architect to pause the evaluation of code at a given line. This allows you to quickly get under the hood of complex chunks of code and inspect the values of variables.
To set a breakpoint, double click in the “gutter” on the line where you’d like evaluation to be paused.
You can set multiple breakpoints in the same script.
Now, when we run code, evaluation will be paused when either breakpoint is reached.
Source the script
The last preparatory step is to source the script you intend to debug. Source the script by typing Ctrl+r, Ctrl+s. Our breakpoints will update visually with a check mark to show we are ready to debug:
Run code
With our breakpoints set, we run the code by calling:
myFun(6)
When a breakpoint is reached, the debug perspective launches automatically.
Note that you can toggle to your previous perspective with the toggler in the top-right corner ().
Inside of the debugging view, we have access to debug-specific commands:
- (F5): execute the current line and move to the next line. If the current line contains a function call, the debugger will step inside of that function.
- (F6): execute the current line of code and move to the next, without stepping into any called functions
- (F7): steps out of the currently executed function and returns to that function’s caller
- (F8): resume code evaluation until the next breakpoint
Conditional Breakpoints
Suppose we would like a breakpoint to trigger only if a certain condition is met. In a trivial example, say we have a loop that will run 10 times, but we only want the breakpoint to trigger on the ninth iteration.
We can set such a condition in the breakpoint window.
Debugging Installed Packages
If you’ve installed a package in Architect via R CMD INSTALL, you can debug it by placing a breakpoint within a function and calling that function.