Reuse objects with a long processing time either by storing those in disk or memory. Uses caching to identify R objects (e.g., data frames, plots, etc.) and allows repeated access to those. Created with the specific goal of skipping the waiting time for summary tables obtained from large 'SQL' tables. It is extensible to other uses, such as caching plots in 'Tabler' dashboards to reduce waiting times.
This R package offers a minimal approach to cache R objects. It is offers similar functions to
rlang::hash(), cachem::cache_mem(), and cachem::cache_disk().
The usage is quite elemental. While this package was create to cache summary tables obtained from large 'SQL' tables, it works with arbitrary R objects, such as linear models.
Here is an example of how to cache results for an lm() output:
library(tinycache)
fit_model <- function(n, cache) {
key <- hash(n)
cached <- cache$get(key)
if (!is.key_missing(cached)) {
return(cached)
}
set.seed(123)
mydata <- data.frame(x = seq_len(n), y = seq_len(n) * 2 + rnorm(n))
mycoef <- coef(lm(y ~ x, data = mydata))
cache$set(key, mycoef)
mycoef
}
cache <- dcache(dir = tempdir())
fit_model(5e7, cache) # computed and cached
fit_model(5e7, cache) # reused from disk, no recomputation
cache <- mcache()
fit_model(5e7, cache) # computed and cached
fit_model(5e7, cache) # reused from memory, no recomputation
How to check that it works:
cache <- mcache()
# 1st run
system.time(fit_model(5e7, cache))
# > system.time(fit_model(5e7, cache))
# user system elapsed
# 10.088 1.289 8.278
# 2nd run
system.time(fit_model(5e7, cache))
# > system.time(fit_model(5e7, cache))
# user system elapsed
# 0.000 0.000 0.001