with_cache {filecacher}R Documentation

Cache via a file

Description

If the cache exists, the object is retrieved from the cache. Otherwise, it is evaluated and stored for subsequent retrieval.

Use force=TRUE to ensure the object is evaluated and stored anew in the cache.

The object evaluated must be compatible with the cache type. For example, a cache type of 'csv' or 'parquet' requires a data.frame or similar type.

Usage

with_cache(x, label, cache = NULL, type = NULL, force = FALSE)

Arguments

x

The object to store in the cache. Must be compatible with the cache type.

label

A string to use as the name of the file to cache.

cache

One of the following:

  • The path to an existing directory to use for caching. If NULL (default) uses the current path, using here::here().

  • An existing cache object as generated by file_cache().

type

A string describing the type of cache. Must be NULL or one of 'rds', 'parquet', or 'csv'. If NULL (default), uses 'rds'.

force

If TRUE, forces evaluation even if the cache exists.

Value

The value of x.

Examples

# Create a temporary directory for the cache.
tf <- tempfile()
dir.create(tf)

# A dummy function that logs when it's called.
get_df <- function() {
  message("Getting df ...")
  return(mtcars)
}

# Use the resulting object in `with_cache()`.
# 1) The first time, the message is printed.
# 2) The second time, the object is pulled from the cache, with no message.
all.equal(with_cache(get_df(), "df", cache = tf), mtcars)
all.equal(with_cache(get_df(), "df", cache = tf), mtcars)

# `with_cache` is designed to be compatible with piping.
get_df() |>
  with_cache("df", cache = tf) |>
  all.equal(mtcars)


# Advanced: If desired, the `cachem` object methods can be used directly.
cache <- file_cache(tf)
cache$get("df") |> # Get objects previously cached using `with_cache`.
  all.equal(mtcars)
cache$set("df2", mtcars) # Set objects using `$set`.
cache$get("df2") |>
  all.equal(mtcars)

unlink(tf, recursive = TRUE)

[Package filecacher version 0.2.9 Index]