cache: Cache the result of a block of code to disk

Description Usage Arguments Details Value Examples

Description

When loading large amounts of data or performing a long running computation, it is ofen desirable to cache the results. This function assumes that you wish to run a block of code, assigning the resulting value to a variable. That value will then be cached to disk, and the second time that the code is run, the value will be read from disk.

Usage

1
cache(file, expr)

Arguments

file

The path to a file in which the results should be cached. It is preferred that the file name should end in .rds to indicate that it is a serialized R object. Cf. saveRDS.

expr

A block of code delimited by braces {}.

Details

Caveats: Caching a value is only worthwhile if the roundtrip to disk is less expensive than the computation itself. Only the last value in the block of code will be cached. (That last value can include assignment.)

Value

The last value computed in expr.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# On the first run, the value is computed and cached to disk
f <- tempfile(fileext = ".rds")
a <- cache(f, {
      Sys.sleep(2)
      z <- 10
     })
a # 10
z # 10
rm(z)

# On the second run, the value is retrieved from disk
b <- cache(f, {
      Sys.sleep(2)
      z <- 10
     })

identical(a, b) # The value from disk is the same as the last computed value
exists("z")     # The block of code was not executed

lmullen/mullenMisc documentation built on May 21, 2019, 7:35 a.m.