How to define “hidden global variables” inside R packages?

喜夏-厌秋 提交于 2019-12-19 05:46:30

问题


I have the following 2 functions in R:

exs.time.start<-function(){
  exs.time<<-proc.time()[3]
  return(invisible(NULL))
}

exs.time.stop<-function(restartTimer=TRUE){
  if(exists('exs.time')==FALSE){
    stop("ERROR: exs.time was not found! Start timer with ex.time.start")
  }
  returnValue=proc.time()[3]-exs.time
  if(restartTimer==TRUE){
    exs.time<<-proc.time()[3]
  }
  message(paste0("INFO: Elapsed time ",returnValue, " seconds!"))
  return(invisible(returnValue))
}

The function exs.time.start creates a global variable (exs.time) with the CPU time of the moment when I called the function.

The function exs.time.stop access that global variable and return the time between the execution of exs.time.start and exs.time.stop.

My objective is to create a package in R with these two functions. How can I define that global variable (exs.time) to be a variable that's invisible to the user, so he couldn't see this variable in the R Global Environment?

Can I define this variable to be a "hidden" global variable inside the R package environment/namespace?

It's my first time working with packages, so I don't know exactly how to use very well the namespace file when defining packages. I'm creating my package using R Studio and Roxygen2.

Any help or suggestion would be great!


回答1:


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.




回答2:


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!



来源:https://stackoverflow.com/questions/34254716/how-to-define-hidden-global-variables-inside-r-packages

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!