Last active
December 11, 2015 04:28
-
-
Save vkryukov/4544831 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Replaced
match.call()
withlist(...)
and usesaveRDS/readRDS
as per @hadley's suggestion