01 / 21

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.

R Programming 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.

Bug
An error or unexpected behavior in your code
Debugger
A tool that lets you pause and inspect running code
Breakpoint
A marker that tells R where to pause execution

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.

print() Approach
You must guess where the bug is, add print() calls, re-run, read output, remove prints, repeat
Debugger Approach
Pause anywhere, inspect everything interactively, step forward line by line, no code changes needed

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.

Normal Mode Prompt: > Code runs freely breakpoint Browse Mode Prompt: Browse[1]> Code is paused Browse Mode Commands n next line c continue Q quit debug ls() list variables Type any variable name to see its value

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.

calculate_mean <- function(x) { total <- sum(x) browser() # Execution pauses HERE result <- total / length(x) return(result) }

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.

debug(calculate_mean) # Flag the function calculate_mean(c(10, 20, 30)) # Now it pauses at line 1 # When done debugging: undebug(calculate_mean) # Remove the flag

browser() vs debug()

browser() line 1: total <- sum(x) line 2: browser() ★ PAUSE line 3: result <- total / n line 4: return(result) Placed inside code Pauses at exact line debug() line 1: total <- sum(x) ★ line 2: n <- length(x) line 3: result <- total / n line 4: return(result) Called before running Pauses at first line vs

How to Debug Step by Step

1
Identify the symptom: What output is wrong? What error message appeared?
2
Set a breakpoint: Insert browser() before the suspicious line, or call debug(my_function).
3
Run the code: Execute normally. R will pause at the breakpoint and show Browse[1]>.
4
Inspect variables: Type variable names to see their values. Use ls() to list all local variables.
5
Step forward: Press n to execute the next line and see how values change.
6
Fix and clean up: Once you find the bug, press Q to quit, fix the code, and remove browser() or call undebug().

Example 1: Using browser()

Suppose this function returns the wrong answer. Let's debug it:

calc_area <- function(radius) { diameter <- radius + 2 # Bug! Should be * 2 browser() area <- pi * (diameter / 2)^2 return(area) }

Inside the Browse Session

Here is what the interactive session looks like in the R console:

> calc_area(5) Called from: calc_area(5) Browse[1]> diameter [1] 7 # Should be 10! Browse[1]> radius [1] 5 # Input is correct Browse[1]> ls() [1] "diameter" "radius" Browse[1]> n # Step to next line debug at #4: area <- pi * (diameter/2)^2 Browse[1]> Q # Quit, go fix the bug

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:

grade_score <- function(score) { if (score >= 90) return("A") if (score >= 80) return("B") if (score >= 60) return("C") # Bug: threshold should be 70 return("F") } debug(grade_score) # Flag it grade_score(65) # Pauses at line 1

Example 3: Debugging a Loop

browser() inside a loop lets you inspect each iteration:

running_total <- function(nums) { totals <- c() for (i in seq_along(nums)) { if (i == 3) browser() # Pause on iteration 3 totals[i] <- sum(nums[1:i]) } return(totals) }

Execution Flow with Debugging

Write / Edit Code Set breakpoint browser() or debug(fn) Run Code Browse Mode: Inspect n, c, Q, ls(), var names Found bug? Fix it! Code works! No bug

Bonus Tools: debugonce() & traceback()

debugonce(fn)
Like debug(), but only pauses once. No need to call undebug() afterwards: it automatically turns off after one use.
traceback()
Call after an error occurs. It shows the call stack: the chain of function calls that led to the error, from most recent to oldest.

Common Mistakes

✕ Forgetting to Remove browser()
Leaving browser() in your code means it will pause every time anyone runs that function. Always clean up when done.
✕ Forgetting undebug()
After calling debug(fn), your function will keep pausing forever until you call undebug(fn). Use debugonce() to avoid this.
✕ Typing "n" as a Variable
In Browse mode, typing n means "next line," not "show me the variable n." To inspect a variable named n, type print(n) instead.

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

What will the student discover is the root cause of the bug?