Stash an object after the first time is is created and re-load it the next time. If the code that generates the object is changed or any of its dependencies change, the code is re-evaluated and the new object is stashed.

stash(var, code, depends_on = NULL, functional = NULL, verbose = NULL)

Arguments

var

A variable to stash (as a string containing the name of the variable). If functional is FALSE, this must be a string containing a valid R variable name. If functional is TRUE, this can be an arbitrary R object.

code

The code to generate the object to be stashed.

depends_on

A vector of other objects that this one depends on. Changes to these objects will cause the re-running of the code, next time.

functional

If TRUE, return the object rather than setting in the global environment (default FALSE).

verbose

Whether to print action statements (default TRUE).

Value

The resulting object if functional is TRUE, otherwise NULL Returns NULL (invisibly).

Details

The var parameter is used as the key for the stash. Therefore, stashing a value using the same var name will overwrite the existing stash, even if the new call is made in a different context (environment). To stash multiple logically independent values, each of which should be updated separately, use separate vars for each stash.

If functional is FALSE, the value of var is also used to determine the name of the variable to which the resulting object should be assigned, and it must therefore be a string containing a valid R variable name. If functional is TRUE, the resulting object is simply returned, and there are no restrictions on the value of var, and it can be an arbitrary object.

Examples

# \donttest{
# A value that is used to create `rnd_vals`.
x <<- 1e6 # The `<<-` is not normally required, just for this example.

# Stash the results of the comuption of `rnd_vals`.
stash("rnd_vals", depends_on = "x", {
  # Some long running computation.
  rnd_vals <- rnorm(x)
})
#> Stashing object.

# Stash using an arbitrary object as key (only allowed if functional==TRUE)
stash(list(letters, cars), { 7 }, functional = TRUE)  # styler: off
#> Stashing object.

# Remove directory for this example - do not do in real use.
unlink(".mustashe", recursive = TRUE)
# }