Skip to content

Instantly share code, notes, and snippets.

@vkryukov
Last active December 11, 2015 04:28
Show Gist options
  • Save vkryukov/4544831 to your computer and use it in GitHub Desktop.
Save vkryukov/4544831 to your computer and use it in GitHub Desktop.
library(digest)
LoadRDataIfExists <- function(fn) {
# Calls _fn_ and caches the result on disk, unless the cache already exists
#
# _fn_ should be a function with signature _fn(filename, ...)_
# If cache file exists and is recent, load data from it.
# Otherwise call the original function.
function (filename, ...) {
param.hash = digest(c(fn, list(...))) # Cache file names depends on params/fn def
cache.filename <- paste(filename, param.hash, 'RData', sep = '.')
if (file.exists(cache.filename) &
file.info(filename)$mtime <= file.info(cache.filename)$mtime) {
# .RData exists, we need to load it
return (readRDS(cache.filename))
} else {
# .RData either doesn't exist or outdated, need to replace it
result = do.call(fn, c(list(filename), ...))
saveRDS(result, file = cache.filename)
return (result)
}
}
}
@vkryukov
Copy link
Author

Replaced match.call() with list(...) and use saveRDS/readRDS as per @hadley's suggestion

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment