library(cache) knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "man/figures/README-", out.width = "100%" )
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).
You can install the package directly from Github.
if (!require(devtools)) install.packages("devtools") devtools::install_github("pmcharrison/cache")
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:
.cache
- Whether or not to use cache on the current call..cache_memory
- Enables in-memory caching..cache_dir
- Directory in which to save cached files..cache_force
- If TRUE, an error will be thrown if the current call
cannot be found in the cache. Useful for debugging.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()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.