edit global variable in my package
Scenes
Recently I'd had a package R language, mainly encapsulated some of the performance function. These features have been added to the back, a bit like framework called. This involves the problem of global variables within the package. I assume that the package name mypackage
, I want to implement a number of incremental acquisition function.
Code 1
COUNT <- 1
get_sn <- function(){
COUNT <- COUNT + 1
return(COUNT)
}
Called multiple times mypackage::get_sn()
, the results were 2, this should not be construed COUNT reason as global variables.
Code 2
COUNT <- 1
get_sn <- function(){
COUNT <<- COUNT + 1
return(COUNT)
}
Call mypackage::get_sn()
error. The error was Error in COUNT <<- COUNT + 1 : 无法改变被锁定的联编'COUNT'的值
.
I understand COUNT became defined const
, it is read only
the.
The attempt by directly modifying, mypackage::COUNT <- 100
is not enough, the error is Error in mypackage::COUNT <- 1 : 找不到对象'mypackage'
. Here I can only read but not write to understand, with other languages namespace
on using still some gaps.
solution
Variables can be explicitly modified by the environment.
Code 3
myenv <- new.env()
myenv$COUNT <- 1
get_sn <- function(){
myenv$COUNT <- myenv$COUNT + 1
return(myenv$COUNT)
}
Multiple calls mypackage::get_sn()
can get incremental figures.
Here we should note in particular, mypackage::myenv$COUNT <- 100
direct modifications are being given, find the object.