2

Minimal scenario

Suppose a package which needs to monitor its own usage. For example, the number of times a specific function of the package has been called since the package was loaded.

What is the best way to achieve this?


First idea

I have tried to create a variable inside the .onLoad() function:

## R/zzz.R

.onLoad <- function(libname, pkgname) {
  how_many_times <- 0
}

But this variable is not accessible after the package loading...


Second idea

A variable inside some of the .R file. And the use of the scoping assignement operator <<-:

## R/somefile.R

#' @exports
how_many_times <- 0

#' @exports
count_me <- function() {
  how_many_times <<- how_many_times + 1
  how_many_times
}

But it does not work either! The first defined global how_many_times is not changed when I call the function count_me but it is another variable as a closure inside the function which is modified.

pietrodito
  • 1,783
  • 15
  • 24
  • 2
    Second is an acceptable way to go, and is likely the easiest and most direct. You shouldn't need to remove it manually, as unloading the package should allow R to do garbage-collection naturally (namespace removal). – r2evans Apr 22 '20 at 20:11

0 Answers0