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

梦想的初衷 提交于 2019-12-01 03:51:56

I use package-global environments in a few packages:

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

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!

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