R debugging
last modified November 19, 2026
An error message names a problem, but it rarely says which path led to it. A
debugging session recovers that path: the calls that were active, the values
the arguments had, and the statement that produced the wrong result. R has
tools for each step. traceback prints the calls behind an error,
browser pauses inside a function, debug and
debugonce step through a function statement by statement,
trace inserts a probe without editing the file, and
sys.calls exposes the stack from inside the code. This article
walks through those tools on small scripts and ends with a complete debugging
session. The examples use R 4.5.2.
Reading an error
An uncaught error stops an Rscript run and prints two lines: the error itself
and Execution halted from the front end. The error line has two
parts. The part after Error in is the call that was being
evaluated, and the part after the colon is the condition message. When the
message is written with call. = FALSE, the call is omitted and only
Error: remains. The examples raise their errors with
stop, which takes a message, signals an error, and abandons the
current computation; the error handling
article shows how to catch such errors instead of letting them end the script.
average <- function(x) {
if (length(x) == 0) {
stop("no values to average")
}
sum(x) / length(x)
}
readings <- c(2, 4, 6)
cat("average:", average(readings), "\n")
empty <- numeric(0)
average(empty)
The first call averages three numbers and prints four. The second call passes
an empty vector, so length(x) == 0 is true and stop
signals an error. The message reports average(empty) because that
is the call that was active when the condition was created; the assignment
empty <- numeric(0) is one line above. The script ends because
nothing caught the error, which is why the last line is
Execution halted.
$ Rscript failure.R average: 4 Error in average(empty) : no values to average Execution halted
Inspecting values
The oldest debugging technique is to print the values that matter. A call to
cat can show a length or a class, and str prints the
structure of an object: its type, its dimensions, and the first few values.
This works in every R environment, including a batch script on a server where
no interactive debugger is available. The calls are temporary, so they should
be removed once the bug is found.
clean <- function(x) {
cat("input length:", length(x), "\n")
cat("input class:", class(x), "\n")
str(x)
x[!is.na(x)]
}
values <- c(4, NA, 8, NA, 2)
cat("clean length:", length(clean(values)), "\n")
The output confirms that clean received a numeric vector of length
five with two missing values, and that the subsetting expression returned
three values. str is more informative than print for
lists and data frames, because it shows the type of every column instead of
only the values. When a function returns an unexpected type, a single
str call often locates the change.
$ Rscript inspect.R input length: 5 input class: numeric num [1:5] 4 NA 8 NA 2 clean length: 3
traceback
An interactive R session keeps the last error and prints its call stack when
traceback() is called. Rscript ends the session at the error, so
the script must install an error handler first. options(error = ...)
replaces the default handler; the replacement below prints the three most
recent calls and exits with a non-zero status. traceback numbers
the calls from the outermost, numbered 1, to the innermost.
options(error = function() {
traceback(3)
quit(save = "no", status = 1)
})
inner <- function(x) {
if (x < 0) stop("negative input", call. = FALSE)
sqrt(x)
}
wrapper <- function(x) inner(x)
cat("result:", wrapper(16), "\n")
wrapper(-4)
The successful call prints four. The failing call raises negative
input inside inner, which was called by wrapper,
which was called at the top level. The traceback lists stop as
call 3, inner(x) as call 2, and wrapper(-4) as call 1.
Reading from the bottom up gives the path that led to the failure. The
quit call keeps the exit status non-zero, so a shell script that
runs this file can tell that it failed.
$ Rscript traceback-error.R
result: 4
Error: negative input
3: stop("negative input", call. = FALSE)
2: inner(x)
1: wrapper(-4)
browser
browser() stops execution and opens a debug prompt in the frame
of the function that called it. From that prompt, any R expression can be
evaluated with access to the function's arguments and local variables. The
prompt is written Browse[1]>; the number is the browser level,
which grows when a second browser is entered from the first. Typing
n executes the next statement, c continues to the end
of the function, and Q quits the browser and the current
evaluation.
halve <- function(x) {
browser()
x / 2
}
cat("result:", halve(10), "\n")
The listing is stored in halve.R and sourced from an interactive
session. The call to halve(10) enters the browser before the
division. ls() shows the objects in the function frame, and
print(x) shows the argument. The first n moves to the
division statement and reports its source location; the second executes it and
returns to the caller, where cat prints the result.
$ R --vanilla --quiet
> source("halve.R")
Called from: halve(10)
Browse[1]> ls()
[1] "x"
Browse[1]> print(x)
[1] 10
Browse[1]> n
debug at halve.R#3: x/2
Browse[1]> n
result: 5
> q("no")
debug and debugonce
debug marks a function so that every call enters the debugger, and
undebug removes the mark. debugonce marks the function
for one call only and then clears the mark automatically, which is safer in a
long session. The debugger prints each expression before evaluating it, so the
transcript shows the body of the function one statement at a time. The same
n, c, and Q commands work as in the
browser.
ratio <- function(a, b) {
result <- a / b
result
}
The function is sourced first, then marked with debugonce. The
call ratio(8, 2) reports debugging in and stops at
the opening brace. Two n commands move through the assignment and
the final expression, and the third leaves the function and prints its value.
The line exiting from: ratio(8, 2) separates the function body
from the return value, which is four.
$ R --vanilla --quiet
> source("ratio.R")
> debugonce(ratio)
> ratio(8, 2)
debugging in: ratio(8, 2)
debug at ratio.R#1: {
result <- a/b
result
}
Browse[1]> n
debug at ratio.R#2: result <- a/b
Browse[1]> n
debug at ratio.R#3: result
Browse[1]> n
exiting from: ratio(8, 2)
[1] 4
> q("no")
trace
trace inserts an expression into a function without changing the
file that defines it. The expression is given as a quoted call, and it runs at
the start of the function body in the function's own frame, so it can read the
arguments and local variables. print = FALSE stops
trace from printing the modified function, and
untrace removes the probe. This is useful for a function that
comes from a package or from a file that should stay untouched.
scale_value <- function(x, multiplier) {
x * multiplier
}
invisible(trace(scale_value,
quote(cat("call: scale_value(", x, ", ", multiplier, ")\n", sep = "")),
print = FALSE))
cat("result:", scale_value(5, 3), "\n")
untrace(scale_value)
cat("after untrace:", scale_value(5, 3), "\n")
The traced call prints its two arguments and then returns 15. The
invisible wrapper hides the name that trace would
otherwise print at the top level. After untrace, the second call
runs the original body and prints no probe line, but the result is the same.
The probe expression is evaluated before the body, so it reports the arguments
as they were received, before any assignment in the function changes them.
$ Rscript trace-calls.R call: scale_value(5, 3) result: 15 after untrace: 15
Reading the call stack
Every active call has a frame, an environment that holds its arguments and
local variables. sys.frames() returns the list of frames and
sys.calls() returns the corresponding calls. A function can
inspect the stack from the inside, which is how a custom error handler can
report more than the default message. parent.frame() returns the
environment of the caller, and sys.function(n) returns the
function that belongs to frame n.
level_three <- function() {
cat("frames:", length(sys.frames()), "\n")
print(sys.calls())
}
level_two <- function() level_three()
level_one <- function() level_two()
level_one()
The output shows three frames, one for each function on the way to
level_three. The call list prints in the order the calls were
made, starting with level_one() and ending with
level_three(). The current call to sys.calls is not
part of the list it returns, so the printed list has three entries rather than
four. A larger program can walk the list and print the arguments of each call
when it fails.
$ Rscript call-stack.R frames: 3 [[1]] level_one() [[2]] level_two() [[3]] level_three()
A complete debugging session
The function below is supposed to return the two highest scores from a vector,
but it returns the two lowest. The name and the call both look right, and the
code contains no error message, so the only way to see the problem is to
inspect the intermediate vector. The session sources the file, calls the
function, marks it with debugonce, and steps to the line after the
sort.
top_scores <- function(scores, n = 2) {
ranking <- scores[order(scores)]
head(ranking, n)
}
The first call returns 79 88, the two smallest values. The
debugger stops at the opening brace, then at the assignment, then at the
head call. At that point ranking is available, and
printing it shows 79 88 91 95, which is sorted from smallest to
largest. order returns the positions that would sort a vector in
ascending order; the function takes the first two, so it keeps the lowest
scores. After the fixed file is sourced, the same call returns
95 91.
$ R --vanilla --quiet
> source("top_scores.R")
> top_scores(c(88, 95, 79, 91))
[1] 79 88
> debugonce(top_scores)
> top_scores(c(88, 95, 79, 91))
debugging in: top_scores(c(88, 95, 79, 91))
debug at top_scores.R#1: {
ranking <- scores[order(scores)]
head(ranking, n)
}
Browse[1]> n
debug at top_scores.R#2: ranking <- scores[order(scores)]
Browse[1]> n
debug at top_scores.R#3: head(ranking, n)
Browse[1]> ranking
[1] 79 88 91 95
Browse[1]> n
exiting from: top_scores(c(88, 95, 79, 91))
[1] 79 88
> source("top_scores_fixed.R")
> top_scores(c(88, 95, 79, 91))
[1] 95 91
> q("no")
The fix
The corrected function passes decreasing = TRUE to
order, so the positions run from the largest score to the
smallest. head then keeps the two highest values. The same result
could be written with sort(scores, decreasing = TRUE)[1:n] or with
order(-scores), but the explicit argument states the intent most
clearly. The repaired file is run as a script to confirm the output outside the
debugger.
top_scores <- function(scores, n = 2) {
ranking <- scores[order(scores, decreasing = TRUE)]
head(ranking, n)
}
cat(top_scores(c(88, 95, 79, 91)), "\n")
The script prints the two highest scores and exits normally. The debugging session found the bug by inspecting a value, not by reading the error message, because there was no error message. That is the common case: a function returns a plausible but wrong result, and the debugger shows which intermediate value departs from the expectation.
$ Rscript top_scores_fixed.R 95 91
Next steps
The error handling article shows how to
turn these signals into handlers, custom conditions, and cleanup code. The
functions article explains the environments
that browser and sys.frames expose, and the
control flow article covers the loops and
branches that a stepped-through function executes. The
subsetting article explains the index vectors
that order returns in the final example.
Source
In this article we read the call and message of an error, printed intermediate
values with cat and str, and used
traceback to see the path behind a failure. browser
paused inside a function, debugonce stepped through a call,
trace added a probe without editing a file, and
sys.calls exposed the active stack. The final session used the
debugger to find an ascending sort in a function that needed a descending one.
The error handling article shows what to
do with the conditions once they are found.
Author
List all R Language tutorials.