0

I am writing a package for the first time and I am trying to understand how it works in principle.

I need a variable to be available to many functions within the package. The common suggestion is to use a new environment that you specifically create for this purpose from within the package. For example, here:

How to define "hidden global variables" inside R packages?

or in this snippet of code:

https://github.com/eddelbuettel/rcppgsl/blob/master/R/inline.R#L19-L34

Based on this suggestion, right now my code starts with:

.pkg_env <- new.env(parent=emptyenv())

Yet, I cannot reconcile this with the principle that "the code in a package is run when the package is built" as mentioned here (https://r-pkgs.org/r.html#understand-when-code-is-executed). Perhaps, I am missing something in the way environments are managed in R, but I would guess you need that line to be run at load to create the environment.

non87
  • 115
  • 1
  • 8
  • Many packages have an option or options for the use by functions. – IRTFM Nov 23 '20 at 02:49
  • Well, the environment will be created either way and will be available to you once your package has loaded. What problem are you running into in particular? Is there some behavior you are observing that isn't clear? This is basically what that [last_plot](https://github.com/tidyverse/ggplot2/blob/1c09bae2aa24320bcb4891c664cccc16efc86a8a/R/plot-last.r) function does in ggplot2 using a closure rather than an environemnt. – MrFlick Nov 23 '20 at 03:45
  • 1
    It a better way to say this maybe is that the environment will be created for you when you build the package, but it will be saved within the package contents so when you load the package, it will still exist. – MrFlick Nov 23 '20 at 03:58
  • @MrFlick your last comment actually clarified the issue to me. So the environment is "shipped" with the binary and will be there when installing the package, correct? – non87 Nov 23 '20 at 14:01
  • 1
    Basically yeah. That would be a reasonable mental model. – MrFlick Nov 23 '20 at 14:08

0 Answers0