Last active
November 8, 2017 04:14
-
-
Save goldingn/0c8044daf0b21518ea4d2465cba6046a to your computer and use it in GitHub Desktop.
quick and dirty caching of R objects, via a %<--% operator
This file contains 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
# 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