如何在R包中定义“隐藏的全局变量”?

问题描述 投票:8回答:2

我在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))
}

函数exs.time.start使用我调用函数时的CPU时间创建一个全局变量(exs.time)。

函数exs.time.stop访问该全局变量并返回执行exs.time.startexs.time.stop之间的时间。

我的目标是使用这两个函数在R中创建一个包。如何将全局变量(exs.time)定义为对用户不可见的变量,因此他无法在R全局环境中看到此变量?

我可以将此变量定义为R包环境/命名空间内的“隐藏”全局变量吗?

这是我第一次使用包,所以我不确切知道如何在定义包时很好地使用命名空间文件。我正在使用R Studio和Roxygen2创建我的包。

任何帮助或建议都会很棒!

r r-package
2个回答
7
投票

我在几个包中使用package-global环境:

并且可能还有更多,但你明白了。


7
投票

感谢您分享您的包裹@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))
}
  • 在我的函数定义之前,我已经在我的R文件中创建了一个new.env()环境。
  • 我使用assign()来访问环境并更改全局变量的值!

隐藏变量,一切正常!多谢你们!

© www.soinside.com 2019 - 2024. All rights reserved.