A simple pass-through cache for complex or long running operations
Source:R/zz-api-cache.R
cached.Rd
executes expr and saves the output as an RDS file indexed by has of code in expr and the hash of input variables (which should contain any variable inputs)
Usage
cached(
.expr,
...,
.nocache = getOption("cache.disable", default = FALSE),
.cache = getOption("cache.dir", default = rappdirs::user_cache_dir("ggrrr")),
.prefix = getOption("cache.item.prefix", default = "cached"),
.stale = getOption("cache.stale", default = Inf)
)
Arguments
- .expr
the code the output of which requires caching. Other than a return value this should not create side effects or change global variables.
- ...
inputs that the code in expr depends on and changes in which require the code re-running, Could be Sys.Date()
- .nocache
an option to defeat the caching which can be set globally as options("cache.disable"=TRUE)
- .cache
the location of the cache as a directory. May get its value from options("cache.dir") or the default value of rappdirs::user_cache_dir("ggrrr")
- .prefix
a name of the operation so that you can namespace the cached files and do selective clean up operations on them
- .stale
the length of time in days to keep cached data before considering it as stale. can also be set by options("cache.stale")
Examples
colName = "Petal.Width"
{
iris[[colName]]
} %>% cached(iris, colName, .prefix="example", .cache=tempdir())
#> caching item: /tmp/Rtmp6208e5/example-4d33d39f25b44f2dd0e3f1c284e46470-7cbba346e54f9b12142893d1b0bc7858.rda
#> [1] 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 0.2 0.2 0.1 0.1 0.2 0.4 0.4 0.3
#> [19] 0.3 0.3 0.2 0.4 0.2 0.5 0.2 0.2 0.4 0.2 0.2 0.2 0.2 0.4 0.1 0.2 0.2 0.2
#> [37] 0.2 0.1 0.2 0.2 0.3 0.3 0.2 0.6 0.4 0.3 0.2 0.2 0.2 0.2 1.4 1.5 1.5 1.3
#> [55] 1.5 1.3 1.6 1.0 1.3 1.4 1.0 1.5 1.0 1.4 1.3 1.4 1.5 1.0 1.5 1.1 1.8 1.3
#> [73] 1.5 1.2 1.3 1.4 1.4 1.7 1.5 1.0 1.1 1.0 1.2 1.6 1.5 1.6 1.5 1.3 1.3 1.3
#> [91] 1.2 1.4 1.2 1.0 1.3 1.2 1.3 1.3 1.1 1.3 2.5 1.9 2.1 1.8 2.2 2.1 1.7 1.8
#> [109] 1.8 2.5 2.0 1.9 2.1 2.0 2.4 2.3 1.8 2.2 2.3 1.5 2.3 2.0 2.0 1.8 2.1 1.8
#> [127] 1.8 1.8 2.1 1.6 1.9 2.0 2.2 1.5 1.4 2.3 2.4 1.8 1.8 2.1 2.4 2.3 1.9 2.3
#> [145] 2.5 2.3 1.9 2.0 2.3 1.8
#> attr(,"cache-path")
#> [1] "/tmp/Rtmp6208e5/example-4d33d39f25b44f2dd0e3f1c284e46470-7cbba346e54f9b12142893d1b0bc7858.rda"
#> attr(,"cache-date")
#> [1] "2024-06-13 11:00:09 BST"