Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's similar to an #ifdef DEBUG in R?

Tags:

r

I'm writing R code where I would like to have it run either in "non-debug" or "debug" mode. Under the debug mode, I would like the code to print-out runtime information.

In other languages, I would typically have some sort of print function that does nothing unless a flag is turned on (either for compilation or runtime).

For example, I can use #ifdef DEBUG (in compilation time), or set a debug level in run time.

What would be the equivalent way of doing this in R?

like image 474
Ron Avatar asked Jun 08 '11 22:06

Ron


3 Answers

Same thing, minus the preprocessor:

  • Define a global variable variable (or use an options() value)
  • Insert conditional code that tests for the variable
  • Works with your functions (adding ..., verbose=options(myVerbose)), in your packages, etc pp
  • I have also used it in R scripts (driven by littler) using the CRAN package getopt to pick up a command-line option --verbose or --debug.
like image 121
Dirk Eddelbuettel Avatar answered Oct 14 '22 02:10

Dirk Eddelbuettel


A slightly fancier version of Dirk's answer:

is_debug_mode <- function()
{
  exists(".DEBUG", envir = globalenv()) && 
    get(".DEBUG", envir = globalenv())
}

set_debug_mode <- function(on = FALSE)
{
  old_value <- is.debug.mode()
  .DEBUG <<- on
  invisible(old_value)
}

Usage is, e.g.,

if(is_debug_mode())
{
  #do some logging or whatever
}

and

set_debug_mode(TRUE)   #turn debug mode on
set_debug_mode(FALSE)  #turn debug mode off
like image 4
Richie Cotton Avatar answered Oct 14 '22 02:10

Richie Cotton


It might also be worth looking at the Verbose class in the R.utils package, which allows you very fine control for printing run-time information of various sorts.

like image 2
nullglob Avatar answered Oct 14 '22 01:10

nullglob