10

I'm doing a data analysis and created a package to store my vignettes and data, as explained here.

I want to set some variables that would be available to all my package functions.

These variables define: the path to data sets, the measurements characteristics (such as probes positions), physical constants and so on.

I have read that one recommended way to store such variables is to use environments.

The question is, where do I put the script that creates the environment?

I thought about putting it in the onLoad method, to be sure it's executed when the package is loaded.

epo3
  • 2,991
  • 2
  • 33
  • 60
Ben
  • 6,321
  • 9
  • 40
  • 76
  • 2
    Regarding paths, you could define them as options retrieving each with `getOption` or as environment variables retrieving each with `Sys.getenv` and defining their values in your `.Rprofile`. This would make your package independent of the particular paths on your machine. If making it only semi-independent is ok then you could hard code a default configuration so that initially nothing need be set in your `.Rprofile` yet you could still change them without modifying the package. – G. Grothendieck Jan 31 '17 at 12:17

1 Answers1

11

If you put it in the .onLoad function (not method), you'll have to use the assign function to ensure the environment gets created in your package namespace.

.onLoad <- function(libname, pkgname)
{
    # ...
    assign("myPackageEnvironment", new.env(), parent.env())
    # ...
}

But you can also just put it in open code:

myPackageEnvironment <- new.env()

Informally, you can think of your package's .R files as being sourced one after another into the environment of your package namespace. So any statements that run in open code will create objects there directly.

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
  • This means I could even just declare my variables in an R file (not in an environment) and use them in my package functions? – Ben Jan 31 '17 at 10:49
  • No, you can't do that. Objects created in the package namespace are locked, so you can't change their values after loading. The thing with environments is that while the _environment object_ is locked, its _contents_ are still modifiable. – Hong Ooi Jan 31 '17 at 11:12
  • But if my variables are constant, not supposed to be changed after package loading, that could work, wouldn't it? – Ben Jan 31 '17 at 13:05
  • 1
    Let me rephrase. Objects in the package namespace are locked _at compile time_, so they can't be changed when the user loads the package. This means you can store static objects like functions, class definitions etc, but not anything that is determined at runtime. – Hong Ooi Feb 04 '17 at 12:10