Debugging with
traceback() in R
Learn how to use traceback() to pinpoint exactly where an error occurred in your R code: read the call stack, trace nested functions, and fix bugs faster.
What Happens When R Hits an Error?
When R encounters a problem it cannot resolve, it stops execution and prints an error message. But the message alone is often not enough to tell you which function in your code caused the problem, especially when functions call other functions.
Introducing traceback()
traceback() is a built-in R function that displays the call stack: the sequence of function calls that were active at the moment the most recent error occurred. Think of it as a trail of breadcrumbs leading back to the source of the bug.
The Call Stack Explained
A call stack is the chain of functions that are currently executing. When function A calls function B, which calls function C, R keeps track of all three. If C fails, the call stack shows: A → B → C.
How traceback() Works
traceback() vs. Other Debugging Tools
| traceback() | browser() | debug() | |
|---|---|---|---|
| Purpose | Show where error occurred | Pause and inspect mid-run | Step through line by line |
| When Used | After an error | Before running code | Before running code |
| Modifies Code? | No | Yes (insert call) | No (flag a function) |
| Complexity | Beginner | Intermediate | Intermediate |
Step-by-Step: Using traceback()
Example 1: Simple Error
Example 2: Nested Functions
Example 3: Real-World Pattern
Reading traceback() Output
traceback() in RStudio
RStudio makes traceback() even easier. When an error occurs, RStudio automatically shows a "Show Traceback" button in the console. Clicking it displays the same call stack you would see from typing traceback() manually.
Scope and Limitations
When traceback() Shines
Common Mistakes
Summary: Quick Reference
| Aspect | Detail |
|---|---|
| Syntax | traceback() |
| Arguments | None (typically) |
| When to call | Immediately after an error |
| Reading order | Bottom-up: #1 is the error site |
| Shows | Function call chain (call stack) |
| Does NOT show | Variable values, warnings |
| Replaced by | The next error that occurs |
| RStudio shortcut | "Show Traceback" button |
Question 1 of 5
What does traceback() display when called after an error in R?
Question 2 of 5
In traceback() output, call #1 represents:
Question 3 of 5
You run the following code in R:
f <- function(x) g(x)
g <- function(y) h(y)
h <- function(z) log(z)
f("text")
R returns: Error in log(z) : non-numeric argument to mathematical function
If you call traceback(), how many calls will appear in the output?
Question 4 of 5
Which of the following will replace a stored traceback?
Question 5 of 5
Which of the following is NOT a limitation of traceback()?