Skip to content

Instantly share code, notes, and snippets.

@dholstius
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dholstius/1f2c85ea647435e5719e to your computer and use it in GitHub Desktop.
Save dholstius/1f2c85ea647435e5719e to your computer and use it in GitHub Desktop.
Evaluate an expression and save the result to a file
cached <- function (
file,
expr,
cache_dir = "cache",
compress = "xz",
verbose = TRUE,
force = FALSE
) {
file <- normalizePath(file.path(cache_dir, file), mustWork = FALSE)
if (!file.exists(file) || force) {
if (verbose) {
if (force) {
message("[cached] force:", file)
} else {
message("[cached] miss:", file)
}
}
if (!file.exists(dn <- dirname(file))) dir.create(dn, recursive = TRUE)
saveRDS(obj <- base::force(expr), file = file, compress = compress)
} else {
if (verbose) message("[cached] hit:", file)
obj <- readRDS(file)
}
return(obj)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment