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!
At the end of a session the objects in the global environment are usually kept in a single binary file in the working directory called . RData. When a new R session begins with this as the initial working directory, the objects are loaded back into memory.
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))
}
new.env()
, inside my R file, before my function definitions. assign()
to access the environment and change the value of my global variable!The variable is hidden and everything works fine! Thanks guys!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With