Skip to content

Instantly share code, notes, and snippets.

@klmr
Last active August 29, 2015 14:11
Show Gist options
  • Save klmr/4dca6c5b9e72dc4a3a51 to your computer and use it in GitHub Desktop.
Save klmr/4dca6c5b9e72dc4a3a51 to your computer and use it in GitHub Desktop.
Memoize R functions
memoize = function (f) {
force(f)
cache = new.env()
function (...) {
key = capture.output(dput(list(...)))
if (key %in% ls(cache))
return(get(key, envir = cache))
value = f(...)
assign(key, value, envir = cache)
value
}
}
# Usage:
very_expensive_function = memoize(very_expensive_function)
@klmr
Copy link
Author

klmr commented Dec 10, 2014

(Totally untested, unadulterated braindump.)

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