Debugging

Students cheer on the Redhawks during a sporting event at Miami University.

There are a number of ways to debug in the R programming language (without the need for RStudio). However, RStudio does include an additional handy method to make debugging simpler; we will discuss both of these below.

Three Ways to Debug in R

In this section, three methods of debugging will be discussed. Each of these methods can be done in RStudio as well as R. The first method uses the browser() function, the second uses the debug() function, and the third way requires the trace() function.

The code that will be debugged in all these examples is shown below:

Example:

 sumMade <- 0
for(i in 1:10) {
sumMade <- sumMade + i
print(sumMade)
}

browser() function

When the browser() function is used, it can be placed anywhere in the code. However, even though the statement can be embedded anywhere, the function may not run correctly and may not stop the code in the desired location.

Example:

 sumMade <- 0
browser()
for(i in 1:10) {
sumMade <- sumMade + i
print(sumMade)
}

The code will stop after sumMade is set to 0.

debug() function

In R, there is a debug() function, used to target specific pieces of code. To debug a user-written function, debug(function name) can be run. Once the function is ran, the debugger will examine it.

Example:

In debug mode, there are certain hotkeys that can make navigation easier. For example, n can be used to skip to the next line and c can run through an entire loop.

trace() function

The trace() function can be used to put a browser function in R code. The untrace() function can be used to take the trace out.

trace(sumOfNumbers, edit = TRUE)

To get out of tracing mode, the following can be used:

untrace(sumOfNumbers)

RStudio: Setting Breakpoints

In RStudio, there are two ways to set a breakpoint:

  1. Go to a line and click to the left of the line number
  2. Press shift + f10 on whichever line your cursor is on

After placing a breakpoint, the source button needs to be clicked. This button is to the right of the run and run previous buttons. In addition, the command control + shift + s can be used. Once sourced, the run next line button can be used in the debug menu. The shortcut for running the next line is f10.

Need a Refresher?

Go back to the beginner tutorials.