2

I'm debugging R code with browser(). The function pauses the execution of the current R script and allows for inspection. Is it possible to enable/disable the debug mode on the fly, during the execution? With large scripts it would be very handy.

Thanks

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
Mulone
  • 3,603
  • 9
  • 47
  • 69

1 Answers1

9

Your question prompted me to read ?browser. The documentation says you can use the expr= argument to browser to create (the illusion) of conditional debugging. That, combined with a global option should give you what you want.

foo <- function(x) {
  browser(expr=isTRUE(getOption("myDebug")))
  mean(x)
}
foo(1:10)
options(myDebug=TRUE)
foo(1:10)  # invokes browser
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • +1 -- Thanks for reading `browser` for us all! I've always wrapped `browser` in `if` clauses for this purpose, but no longer. – Josh O'Brien Nov 15 '11 at 22:28
  • @JoshO'Brien: you may still want to wrap it in `if` statements... `?browser` says that will be faster than using `expr=`. – Joshua Ulrich Nov 16 '11 at 00:01
  • OK, that's it... Looks like I need to go read `?browser` once and for all! Thanks. – Josh O'Brien Nov 16 '11 at 00:10
  • Super nifty trick. Added it to the debugging tricks compiled here http://stackoverflow.com/questions/1882734/what-is-your-favorite-r-debugging-trick/5156351#5156351 – Ari B. Friedman Nov 16 '11 at 16:43