Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A cache function to cache arbitrary R code #40

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

jimhester
Copy link
Member

This is a proof of concept, caching arbitrary R code.

This uses the existing memoise machinery to compute a hash based on the input code / expression and any additional variables (specified as formulas in ...), so does not take a cache filename.

You can use it with the in-memory cache, but you need to specify the cache up front, otherwise a new cache is created on every invocation.

mem <- cache_memory()
set.seed(42)
cache({runif(2)}, cache = mem)
#> [1] 0.9148060 0.9370754
cache({runif(2)}, cache = mem)
#> [1] 0.9148060 0.9370754
cache({runif(1)}, cache = mem)
#> [1] 0.2861395
cache({runif(1)}, cache = mem)
#> [1] 0.2861395

Improvements would be to use rlang to construct the function and quote the code / extra arguments. We would also need to change how the ... arguments are handled in regular memoise to use rlang::dots_quos() and rlang::tidy_eval().

@jimhester
Copy link
Member Author

jimhester commented Apr 26, 2017

@hadley this is not exactly the API you were prototyping as it does not take a filename parameter, instead the filenames (if you are using the filesystem backend) are a hash of the function body.

#' @export
cache <- function(code, ..., envir = parent.frame(), cache = cache_memory()) {
expr <- substitute(code)
key <- cache$digest(c(expr, lapply(list(...), function(x) eval(x[[2L]], environment(x)))))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is the eval necessary here? Won't list(...) force all the promises?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh because they're formulas

R/cache.R Outdated
f <- function() NULL
body(f) <- expr
environment(f) <- envir
(memoise(f, envir = envir, ..., cache = cache))()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just do cache$set(key, f()) ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good question!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants