Skip to contents

executes .expr and saves the output as an RDS file indexed by hash of code in .expr and the hash of specified input variables (in ..., which should contain any inputs that influence .expr). The expression is evaluated in the current environment and it is up to the user to ensure all significant environmental factors are accounted for in ...

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.

.nocache

an option to defeat the cacheing which can be set globally as options("cache.disable"=TRUE)

.cache

the location of the cache as a directory. May get its value from getOption("cache.path") or the default value which is rappdirs::user_cache_dir(<package_name>)

.prefix

(optional) a name of the operation so that you can namespace the cached files and do selective clean up operations on them with .cache_clear()

.stale

the length of time in days before considering cached data as stale.

Value

the output of .expr which will usually be a value

Examples

colName = "Petal.Width"
{
  iris[[colName]]
} %>% cached(iris, colName, .prefix="example", .cache=tempdir())
#>   [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/RtmpCoIoxQ/example-01b357b3b7c985f0d54559ca3f61f075-ea3c58012762dc304362a798b82145d5.rda"
#> attr(,"cache-date")
#> [1] "2025-09-25 16:06:40 BST"