library(cache)
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/README-",
  out.width = "100%"
)

cache - Caching function outputs

AppVeyor build status Travis build status Coverage status lifecycle

cache is an R package for function output caching, or memoisation.

The memoise package is an effective tool for caching repeated computations in data analysis projects. However, the memoise package cannot (easily) memoise internal functions within R packages, especially when the demand is for file-based memoisation, or when memoisation options need to be exposed to the end user.

This package addresses these problems. It is designed for memoising functions when creating R packages, while allowing subsequent package users to control cache options (e.g. disabling cache, clearing the cache, changing the cache directory).

Installation

You can install the package directly from Github.

if (!require(devtools)) install.packages("devtools")
devtools::install_github("pmcharrison/cache")

Example usage

Define a simple cached function:

f <- function(x, ...) cache({
  message("Computing...")
  c(x, rnorm(1))
}, ...)

The first time it's called, the main body of the function is run.

f(1) 

The second time it's called, the result is loaded from the file-based cache.

f(1)

Our function f can be called with various caching options - see ?cache::cache for details. These options include:

If we call f with cache disabled, we should get a different result.

f(1, .cache = FALSE) # produces a different result

We can also define an in-memory cache. In-memory caches are faster than the default file-based caches.

x <- cache_memory()
f(1, .cache_memory = x)

f(1, .cache_memory = x)

as.list(x)[[1]]

When we're done, we can clear the cache.

clear_cache()


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