Skip to contents

Evaluates an expression — typically an API pull such as a gho_data() / gho_clean() pipeline — and saves the result to an .rds file. On later calls, the saved snapshot is read back instead of re-evaluating the expression, so analyses re-run reproducibly and offline once the data have been fetched.

Usage

snapshot(expr, file, refresh = FALSE, max_age = Inf)

Arguments

expr

An expression producing the object to snapshot. Evaluated lazily — only when no usable snapshot exists (see Details).

file

Path of the snapshot file (conventionally .rds). Read with readRDS() and written with saveRDS().

refresh

Logical. Re-evaluate expr even if a snapshot exists? Default FALSE.

max_age

Numeric. Maximum acceptable snapshot age in days; an older snapshot triggers re-evaluation as if refresh = TRUE. Default Inf (a snapshot never expires).

Value

The snapshotted object: either the value of expr or the contents of file, per the logic above. A message states which of the two was used.

Details

The decision logic is:

  1. If file exists, refresh = FALSE, and the snapshot is younger than max_age days, the snapshot is read and returned. expr is not evaluated.

  2. Otherwise expr is evaluated. A usable result (anything other than NULL, a 0-row data frame, or an empty list) is written to file (directories are created as needed) and returned.

  3. An empty result — the signature of an unreachable API, since DSIR's network functions fail soft — is never written, so a failed refresh cannot destroy a good snapshot. If an older snapshot exists it is returned instead, with a warning; otherwise the empty result is returned as-is.

snapshot() deliberately does not invent file names, manage a cache directory, or hash arguments: you choose the path, so a project can use a fixed name (data/indicators.rds) or a dated one, and the file is plain saveRDS() output readable without DSIR.

To force a re-fetch, pass refresh = TRUE (or delete the file).

See also

gho_data(), sdg_data(), bind_indicators() — the typical producers of snapshotted objects.

Examples

path <- tempfile(fileext = ".rds")

# First call evaluates the expression and writes the snapshot
x <- snapshot(data.frame(a = 1:3), path)

# Second call reads the snapshot; the expression is not evaluated
y <- snapshot(stop("not evaluated"), path)
identical(x, y)

# Force a refresh
z <- snapshot(data.frame(a = 1:5), path, refresh = TRUE)
nrow(z)

unlink(path)
# \donttest{
# Typical use: pin an API pull for a reproducible report
ncd <- snapshot(
  gho_clean(gho_data("NCDMORT3070", "country", wpro_cty)),
  file.path(tempdir(), "ncdmort3070.rds")
)
# }