Skip to content

Instantly share code, notes, and snippets.

@dholstius
Last active Aug 29, 2015
Embed
What would you like to do?
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