# A function for demonstrating the using caching
fun <- function(x, y){
# Generate the cache name (no argument given, so both x and y is used)
nm <- cache_name(cachedir=cachedir)
# If the result is cached, then just return it
if(file.exists(nm)){ return(readRDS(nm)) }
# Do the calculation
res <- x^2 + y + 1
# Wait 1 sec
Sys.sleep(1)
# Save for cache
cache_save(res, nm)
# Return
return(res)
}
# For this example use a temporary directory
# In real use this should not be temporary! (changes between R sessions with tempdir())
cachedir <- tempdir()
# Uncomment to run:
# First time it takes at least 1 sec.
#fun(x=2,y=2)
# Second time it loads the cache and is much faster
#fun(x=2,y=2)
# Try changing the arguments (x,y) and run again
# See the cache file(s)
#dir(cachedir)
# Delete the cache folder
#unlink(cachedir, recursive=TRUE)
# Demonstrate how cache_name() is functioning
# Cache using the all objects given in the function calling, i.e. both x and y
fun <- function(x,y){
x^2 + y + 1
return(cache_name())
}
# These are the same (same values)
fun(x=1,y=2)
fun(1,2)
fun(y=2,x=1)
# But this one is different
fun(x=2,y=1)
# Test: cache using the values specified in the cache_name call
fun2 <- function(x,y){
x^2 + y + 1
return(cache_name(x))
}
# So now its only the x value that change the name
fun2(1,2)
fun2(1,3)
# But this one is different
fun2(3,3)
# And the function named changed the name
Run the code above in your browser using DataLab