Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show context in R debugger?

Tags:

r

debugging

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.

like image 666
Ken Williams Avatar asked Jan 30 '13 15:01

Ken Williams


1 Answers

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.

EDIT

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.

like image 100
Matthew Plourde Avatar answered Oct 19 '22 16:10

Matthew Plourde