Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Globally turn debug messages on and off in R?

Tags:

r

debugging

I am thinking of something like this:

> fx = function(x, y) {
+     if (exists("debugging")) {
+         print(x)
+         print(y)
+     }
+     x+y
+ }
> fx(1, 2)
[1] 3
> debugging = 1
> fx(2, 3)
[1] 2
[1] 3
[1] 5

This way you can write as many debugging messages as you want, and when you want to turn them off, you just

rm(debugging)

The problem is the variable debugging (or any name that you give it) can be removed or created by any other package anytime, which is hard to control. Any ideas?

like image 696
qed Avatar asked Jan 29 '26 21:01

qed


2 Answers

Use an option. If xyz is the name of your package the debugging code in a typical function would do this:

 if (getOption("xyz.debug", FALSE)) { print(x); print(y) }

Then outside the package issue this to turn on debugging:

 options(xyz.debug = TRUE)

or this to turn it off:

 options(xyz.debug = FALSE) # or options(xyz.debug = NULL)

Its not likely that another package will have an option name prefixed with the name of your package.

The main advantages of this approach are that it does not require any infrastructure other than the if (...) ... statements making it quite lightweight and the overhead for using it in the case that debugging is off is just an if and a call to getOption .

like image 163
G. Grothendieck Avatar answered Feb 01 '26 13:02

G. Grothendieck


Another option would be to define a debugging function in your package:

debugging <- local({
   stored.value <- FALSE
   function(bool = NULL)
      if (is.null(bool)) {
         stored.value
      } else {
         stopifnot(is.logical(bool), length(bool) == 1L)
         stored.value <<- bool
      }
})

# default value:
debugging()
# [1] FALSE

# set value
debugging(TRUE)

# check value
debugging()
# [1] TRUE

This should solve your concern about "What if I decide to change the package name later?" I suppose.

like image 34
flodel Avatar answered Feb 01 '26 13:02

flodel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!