From 62094ff1dc3f4284de1164b010ab129956223cf6 Mon Sep 17 00:00:00 2001 From: Jim Hester Date: Mon, 24 Apr 2017 15:10:57 -0400 Subject: [PATCH 1/2] A cache function to cache arbitrary R code --- NAMESPACE | 1 + R/cache.R | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) create mode 100644 R/cache.R diff --git a/NAMESPACE b/NAMESPACE index 1736c94..1b19389 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,6 +1,7 @@ # Generated by roxygen2: do not edit by hand S3method(print,memoised) +export(cache) export(cache_filesystem) export(cache_memory) export(cache_s3) diff --git a/R/cache.R b/R/cache.R new file mode 100644 index 0000000..21052c9 --- /dev/null +++ b/R/cache.R @@ -0,0 +1,18 @@ +#' @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))))) + if (cache$has_key(key)) { + res <- cache$get(key) + if (res$visible) { + res$value + } else { + invisible(res$value) + } + } else { + f <- function() NULL + body(f) <- expr + environment(f) <- envir + (memoise(f, envir = envir, ..., cache = cache))() + } +} From 2198a679c7611348ac042c8070c2cf2b218b0338 Mon Sep 17 00:00:00 2001 From: Jim Hester Date: Wed, 26 Apr 2017 13:41:29 -0400 Subject: [PATCH 2/2] Simplify call --- R/cache.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/cache.R b/R/cache.R index 21052c9..f70a585 100644 --- a/R/cache.R +++ b/R/cache.R @@ -13,6 +13,6 @@ cache <- function(code, ..., envir = parent.frame(), cache = cache_memory()) { f <- function() NULL body(f) <- expr environment(f) <- envir - (memoise(f, envir = envir, ..., cache = cache))() + cache$set(key, f()) } }