Skip to content

Instantly share code, notes, and snippets.

@goldingn
Last active November 8, 2017 04:14
Show Gist options
  • Save goldingn/0c8044daf0b21518ea4d2465cba6046a to your computer and use it in GitHub Desktop.
Save goldingn/0c8044daf0b21518ea4d2465cba6046a to your computer and use it in GitHub Desktop.
quick and dirty caching of R objects, via a %<--% operator
# quick & dirty caching of R objects - run the expression in b iff an RDS file
# for the object doesn't exist, otherwise load the object
`%<--%` <- function (a, b) {
name <- deparse(substitute(a))
file <- paste0(name, ".rds")
if (file.exists(file)) {
obj <- readRDS(file)
} else {
obj <- b
saveRDS(obj, file)
}
assign(name, obj, envir = parent.frame())
}
flush <- function (object) {
name <- deparse(substitute(object))
file <- paste0(name, ".rds")
suppressWarnings(result <- file.remove(file))
invisible(result)
}
# # example:
# foo <- function() {Sys.sleep(3); 1}
# system.time(test %<--% foo() * 2) # slow
# system.time(test %<--% foo() * 2) # fast
# flush(test)
# system.time(test %<--% foo() * 2) # slow
# flush(test)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment