Reputation: 23975
If I've dropped into the R debugger by using options(error=recover)
, how can I get my bearings and see the code around where it's dropped me? For example:
options(error=recover)
solve(matrix(0, nrow=5, ncol=5))
# Error in solve.default(matrix(0, nrow = 5, ncol = 5)) :
# Lapack routine dgesv: system is exactly singular: U[1,1] = 0
#
# Enter a frame number, or 0 to exit
#
# 1: solve(matrix(0, nrow = 5, ncol = 5))
# 2: solve.default(matrix(0, nrow = 5, ncol = 5))
#
# Selection: 1
# Called from: top level
Browse[1]>
At this point if I hit n or return, I just die again and get the recover
prompt, without ever seeing any lines of code. If I do a stack trace (type where
), I can see the call chain, but not the code I'm actually sitting in (at any level of the stack). [Actually I do see a bit of code in this solve
case, but only because one anonymous function is part of the stack so it has no choice but to print its definition rather than its name.]
Any tips?
[EDIT] I'm interested (among others) in the use case where I need to figure out what's going on in someone's package code. I don't control the source, so I can't add a browser()
, and I don't have easy access to the source file, so just a line number wouldn't be much help. I'd mainly just want to see the actual code.
Upvotes: 7
Views: 586
Reputation: 44614
If you also set options(show.error.locations=TRUE)
, R will print the source line number with the error, e.g.
Error in eval(expr, envir, enclos) (from test.R#4) :
test.R
would be the name of your script, and #4 indicates the error occurred on line four.
If you're just using browser
to insert a breakpoint, you can supply some identifying text with browser(text='end of plotting function')
, and then retrieve this text when you are in the browsing session with browserText()
to verify where you are.
If you want to find the location of an error encountered when using an installed function, the standard way is to call debug
on the function, run your code, then step through until you encounter the error. See ?debug
for more details.
If you're the impatient type, however, you could use the following trick to get the line number of the installed function's body where the error occurred when show.error.locations
is set to TRUE
.
s<-paste(c(capture.output(dump('solve.default', file='')),
'solve(matrix(0, nrow=5, ncol=5))'),
collapse='\n')
source(textConnection(s))
Here s
is a string comprised of the definition of solve.default
(the method that gets called on your matrix in the example you provided), and the call that raises the error.
Upvotes: 5
Reputation: 1206
If you like Emacs, I understand that the ess-tracebug package provides this function by moving a cursor to the current line in a source code buffer. ess-tracebug is included in the latest version of ESS mode.
(If the OP doesn't like Emacs, don't vote up my answer: please wait for a better one.)
Upvotes: 2