cache: Cache a function's outputs

Description Usage Arguments Details Note Examples

Description

Caches a function's outputs to avoid repeated computation. By default, the cache is saved to the working directory, within the sub-directory /.cache. In-memory caches are also supported, by passing an memory-cache object (as created by cache_memory()) to the argument .cache_memory.

Usage

1
2
cache(body, .cache = TRUE, .cache_ignore = character(),
  .cache_memory = NULL, .cache_dir = NULL, .cache_force = FALSE)

Arguments

body

(R code) The body of the function to memoise, typically wrapped in curly braces ({}).

.cache

(Logical scalar) Whether or not to use cache on the current call. If FALSE, no results are loaded or saved to the cache.

.cache_ignore

(Character scalar) By default, all function arguments beginning with '.cache' are ignored for caching purposes; these variables are assumed not to affect function outputs. Additional arguments to ignore can be specified with this parameter.

.cache_memory

(Logical scalar) Either NULL (default), in which case a file-based cache will be used, or an in-memory cache as created by cache_memory().

.cache_dir

(Character scalar) Directory in which to save cached files. If NULL, a directory is constructed within the working directory, representing the name of the calling function and the package within which the function was defined (if applicable).

.cache_force

(Logical scalar) If TRUE, an error will be thrown if the current call cannot be found in the cache. Useful for debugging.

Details

Unlike most existing memoisation packages, cache is well-suited for memoising functions within R packages. Its default arguments are chosen so that, in most cases, a function can be cached simply by wrapping its body in a call to cache().

cache() should be used as a wrapper for the function's body. The code within the body will be memoised. It is possible to add additional code before the call to cache(); such code is typically used to preprocess the function arguments to make memoisation more efficient. For example, if one of the inputs is a vector representing an unordered set, it might be sensible to sort this vector before making the call to cache().

Note

Caching in the cache package does not check for changes in the code of the memoised function. It is the user's responsibility to clear the cache after updating the source code.

Examples

1
2
3
4
5
6
7
8
# Define a simple cached function
f <- function(x, ...) cache({
  message("Computing...")
  c(x, rnorm(1))
}, ...)
f(1)
f(1) # produces the same result
f(1, .cache = FALSE) # produces a different result

pmcharrison/cache documentation built on May 7, 2019, 4:42 p.m.