0

Reproducible example:

Inspired from Hadley book on pacakges:

Create a new empty package called test with NAMESPACE file:

## file NAMESPACE
exportPattern("^[[:alpha:]]+")

And an R file R/package_var.R:

## file R/package_var.R
var <- 0

change_var <- function() {
var <<- 1
}

Then build the package.


Now if you test the package in a new R session:

> library(test)
> var
0
> change_var()
Error in change_var() : 
cannot change value of locked binding for 'var'

But right after this example Hadley states:

you can’t change the binding for objects in the package namespace (well, at least not without trying harder than this).

What is the hard way Hadley is talking about?

pietrodito
  • 1,783
  • 15
  • 24
  • You have just missed what Hadly said. He stated later in the chapter that you should use an environment to bind your variable if you want to change that variable. Just continue reading for several lines, you will find that. Try adding lines of `the <- new.env(parent = emptyenv())` and `the$var <- 0`. – Liang Zhang Jul 09 '23 at 08:34
  • You cannot change a variable binding to the environment of a package. And I do think you have read that lines because the sentence you quote is under the same error you have found. – Liang Zhang Jul 09 '23 at 08:37
  • See https://stackoverflow.com/questions/76599995/assign-versus-assignment-operator/76600761#76600761 – G. Grothendieck Jul 09 '23 at 12:37

1 Answers1

0

One solution is to use the unlockBinding function as noted in this other question:

change_var <- function() {
  unlockBinding("var", as.environment("package:test"))
  assign("var", 2, as.environment("package:test"))
}
pietrodito
  • 1,783
  • 15
  • 24