简体   繁体   中英

could not assign value to global variable in package of R

I'm building a package which has a global variable, the code is as below:

at <- NA 
get.at <- function() {
  if (is.na(at)) {
    at <<- 1
  }
  at
}

But when I call get.at() , it raises an error:

Error in get.at() : cannot change value of locked binding for 'at'

How can I solve this problem?

EDIT:

  1. at could not be changed because the environment is sealed after the package is loaded. But it's possible to call get.at() in custom function .onLoad or .onAttach successfully.

  2. Another solution is to create a variable belonging to an internal environment as @daniel said.

Try to have a look on ?unlockBinding , maybe you first have to open the binding in your package before you can change the value. This is the part of the help file in R that might help you:

e <- new.env()
assign("x", 1, envir = e)
get("x", envir = e)
lockBinding("x", e)
try(assign("x", 2, envir = e)) # error
unlockBinding("x", e)
assign("x", 2, envir = e)
get("x", envir = e)

EDIT: I am not sure if this will actually work out properly in a package. One possible solution is to create another R source file zzz.R and create there an environment where the variable lives in and assign there the default values. zzz.R :

.PkgEnv <- new.env()
assign("at",NA, envir = .PkgEnv)

And then you could change your code in such a way, that you access always the variable from the environment you are interested in:

get.at <- function(){
  if(is.na(get("at",envir=.PkgEnv))){
    assign("at",1,envir=.PkgEnv)
  }
  get("at",envir=.PkgEnv)
}

I just tested it in a test package and it worked out, although I am not sure if this is the 'recommended way of the R core team'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM