Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205372

How to memoise a function at package startup in R

$
0
0

I work on an R package which wraps API calls. In order to reduce the number of actual calls and to speed things up, I memoise the function making the API call. To do so, I created the following function, which allows to set the cache directory:

memoise_fromJSON <- function(cache_dir = tempdir()) {
  memoise::memoise(jsonlite::fromJSON,
                   cache = memoise::cache_filesystem(cache_dir))
}

To create the memoised function I use

memoised_fromJSON <- memoise_fromJSON()

Now, since I need the memoised function many times within my package, I would like to memoise the function at package startup. I tried

.onLoad <- function(libname, pkgname) {
  memoised_fromJSON <- my_package:::memoise_fromJSON()
}

but I still need to run memoised_fromJSON <- memoise_fromJSON() to get it to work.

So my questions are:

  1. Is there a possibility to memoise a function at package startup?
  2. If so, how can I memoise the function in a way that it is not visible in the global environment?

I guess, the questions are somehow related. Is my understanding correct that my attempt with .onLoad() does not work because it creates the memoised function within the environment of .onLoad()?


PS: I am aware, that I cannot change the cache_dir at package loading, but I want to set a reasonable default which makes it possible to start without further ado. However, this keeps the possibility to change the cache directory if needed.


Viewing all articles
Browse latest Browse all 205372

Trending Articles