[R-pkg-devel] Best way to cache a dataframe available for all functions in a package
Lionel Henry
||one| @end|ng |rom r@tud|o@com
Fri Nov 26 14:41:14 CET 2021
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 using gmail.com> wrote:
> Dear all,
>
> I am writing a package that needs to load some data from a URL and have
> such data (meta data) available when using other functions in the package,
> and I would like some advice on how to properly manage such situation.
>
>
> My first guess would be to create a function to downloads that meta data,
> and make this function run when loading the package. I am even familiar
> with this, and I could manage.
>
> But the second part, making this sort of data frame available for other
> functions in the package, how can I achieve it? Of course I can call the
> function that downloads and prepares the data at every use of the other
> functions, but that would mean connecting to the Internet again and again.
> So, in other words, is there a way to "cache" into memory a data frame
> (without having to create an object)?
>
> How could I achieve such thing? What are the kind of keywords that I need
> to use when looking for help?
>
> Thank you very much,
>
> --
> Xavier
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-package-devel using r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-package-devel
>
More information about the R-package-devel
mailing list