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

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.startcreates a global variable ( exs.time) with CPU time at the moment I called the function.

The function exs.time.stopto this global variable and returns the time between execution exs.time.startand exs.time.stop.

My goal is to create a package in R with these two functions. How can I define this global variable ( exs.time) as a variable that is invisible to the user so that he cannot see this variable in the R Global Environment?

Can I define this variable as a “hidden” global variable inside the R package environment / namespace?

, , . , R Studio Roxygen2.

!

+7
2

, @Dirk Eddelbuettel

:

.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))
}
  • new.env() R .
  • assign() !

, ! , !

+6

:

  • RcppGSL GSL

  • RPushbullet

, , , .

+6

Source: https://habr.com/ru/post/1619734/


All Articles