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

前端 未结 2 1754
深忆病人
深忆病人 2021-01-11 12:52

I have the following 2 functions in R:

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

exs.time.stop<-functi         


        
相关标签:
2条回答
  • 2021-01-11 13:06

    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!

    0 讨论(0)
  • 2021-01-11 13:06

    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.

    0 讨论(0)
提交回复
热议问题