Skip to content
Prev 7541 / 12125 Next

[R-pkg-devel] Best way to cache a dataframe available for all functions in a package

Hello,

The trick is to store cached objects in an environment. In our team
some of us have started calling this environment "the" to reflect that
the elements in that environment are global singletons.

Create the environment somewhere in your package:

```
the <- new.env(parent = emptyenv())
```

Then you can initialise and/or retrieve like this:

```
my_data <- function() {
  if (is.null(the$data)) {
    the$data <- generate_data()
  }
  the$data
}
```

This is much better than initialising on load. Downloading on load
would slow down loading your package and any packages that depend on
it. Also the download might fail, causing the loading of your package
to fail in turn.

Best,
Lionel
On 11/26/21, X FiM <xfim.ll at gmail.com> wrote: