Using R Debugging Facilities
R provides several built-in debugging facilities to help identify, inspect, and fix errors during code execution. These tools allow developers to pause execution, check variable states, and understand the sequence of function calls that led to an error.
1. Using traceback()
- Shows the call stack after an error has occurred.
- Useful to see which function caused the error and what other functions were called.
> some_function()
> traceback()
2. Using browser()
- Inserts a breakpoint inside a function.
- Execution pauses, and you can interactively inspect and modify variables.
my_function <- function(x) {
browser()
x + 10
}
my_function(5)
3. Using debug() and undebug()
- Used to step through an entire function line by line.
- Helps inspect the flow and variable values at each step.
debug(my_function)
my_function(5)
undebug(my_function)
4. Using recover()
- Gives access to all active function calls when an error occurs.
- Allows the user to browse the environment of each function in the call stack.
options(error = recover)
5. Using trace()
- Allows you to insert code into a function to track its execution.
- Often used for monitoring function calls without editing the function definition.
> trace("mean", tracer = quote(print("mean function called")))
> mean(c(1, 2, 3))
> untrace("mean")
Example
bad_function <- function(x) {
y <- x + z # z is not defined
return(y)
}
# Use debugging tools
debug(bad_function)
bad_function(10)
undebug(bad_function)