browser() & debug()
Step-Through Debugging in R
Learn how to pause execution, inspect variables, and step through code line by line using R's built-in debugging tools.
What Is Debugging?
Debugging is the systematic process of finding and fixing errors (bugs) in your code. Instead of guessing what went wrong, debugging tools let you pause your program mid-execution and look at exactly what is happening inside.
Why Not Just Use print()?
Many beginners scatter print() statements throughout their code to see variable values. While this works for simple cases, it becomes tedious and error-prone as your code grows.
The R Debugging Environment
When R hits a breakpoint, it drops you into a special Browse mode. Your prompt changes from > to Browse[1]>, and you gain access to powerful inspection commands.
The browser() Function
browser() is a function you place directly in your code at the exact line where you want execution to pause. When R reaches that line, it stops and opens Browse mode.
The debug() Function
debug() is called before you run a function. It flags the entire function so that every time it is called, R pauses at the very first line and lets you step through.
browser() vs debug()
How to Debug Step by Step
Example 1: Using browser()
Suppose this function returns the wrong answer. Let's debug it:
Inside the Browse Session
Here is what the interactive session looks like in the R console:
Example 2: Using debug()
When you do not know which line has the bug, use debug() to step through the entire function from the beginning:
Example 3: Debugging a Loop
browser() inside a loop lets you inspect each iteration:
Execution Flow with Debugging
Bonus Tools: debugonce() & traceback()
Common Mistakes
Comparison Summary
| browser() | debug() | debugonce() | |
|---|---|---|---|
| Where placed | Inside your code | Called in console | Called in console |
| Pauses at | Exact line you choose | First line of function | First line of function |
| Persists | Until removed from code | Until undebug() called | One time only |
| Best for | Known suspicious line | Exploring entire function | Quick one-time check |
| Cleanup | Delete the line | undebug(fn) | Automatic |
Question 1 of 5
What happens when R encounters a browser() call during execution?
Question 2 of 5
How do you remove the debugging flag set by debug(my_func)?
Question 3 of 5
In Browse mode, what does typing n do?
Question 4 of 5
You want to pause inside a function only once to check a variable, and then have debugging turn off automatically. Which tool should you use?
Question 5 of 5
A student's function to convert Fahrenheit to Celsius gives the wrong answer. They expect convert_temp(212) to return 100, but it returns 194.2222.
To find the bug, they insert a browser() call before the return statement and inspect the value of the celsius variable.
What will the student discover is the root cause of the bug?