Debugging tools help you find and fix mistakes in your R code. They make it easier to understand what your program is doing step-by-step.
0
0
Debugging tools in R Programming
Introduction
When your R script gives an error and you want to know why.
When your program runs but the results are not what you expect.
When you want to check the value of variables at different points in your code.
When you want to pause your program to see what is happening inside.
When you want to test small parts of your code separately.
Syntax
R Programming
debug(function_name) undebug(function_name) traceback() browser() options(error = recover)
debug() lets you step through a function line by line.
traceback() shows the call stack after an error happens.
Examples
This will start debugging
my_function. You can step through each line when you run it.R Programming
debug(my_function)
my_function(5)After an error, this shows where the error happened in the call stack.
R Programming
traceback()
This pauses the program at that point and lets you inspect variables.
R Programming
browser()
# Put this inside your function where you want to pause executionWhen an error happens, you can pick a frame to debug interactively.
R Programming
options(error = recover)
# This lets you choose where to debug after an error occursSample Program
This program pauses inside my_function so you can check the value of y before continuing.
R Programming
my_function <- function(x) {
y <- x + 1
browser() # Pause here to check values
z <- y * 2
return(z)
}
my_function(3)OutputSuccess
Important Notes
Use debug() to step through functions without changing code.
browser() is useful to pause exactly where you want inside your code.
After fixing bugs, use undebug() to stop debugging a function.
Summary
Debugging tools help find and fix errors by letting you see what your code does step-by-step.
Use debug(), browser(), and traceback() to understand problems.
These tools make coding easier and help you learn how your program works.