How to define "hidden global variables" inside R packages?

Thank you for sharing your packages @Dirk Eddelbuettel

The solution for my question is the following:

.pkgglobalenv <- new.env(parent=emptyenv())

exs.time.start<-function(){
  assign("exs.time", proc.time()[3], envir=.pkgglobalenv)
  return(invisible(NULL))
}

exs.time.stop<-function(restartTimer=TRUE){
  if(exists('exs.time',envir=.pkgglobalenv)==FALSE){
    stop("ERROR: exs.time was not found! Start timer with exs.time.start")
  }
  returnValue=proc.time()[3]-.pkgglobalenv$exs.time
  if(restartTimer==TRUE){
    assign("exs.time", proc.time()[3], envir=.pkgglobalenv)
  }
  message(paste0("INFO: Elapsed time ",returnValue, " seconds!"))
  return(invisible(returnValue))
}
  • I've created an environment with new.env(), inside my R file, before my function definitions.
  • I've used assign() to access the environment and change the value of my global variable!

The variable is hidden and everything works fine! Thanks guys!


I use package-global environments in a few packages:

  • RcppGSL stores config info about the GSL libraries

  • RPushbullet stores some user-related meta data

and there are probably some more but you get the idea.

Tags:

R

R Package