File: loadCache.R

package info (click to toggle)
r-cran-r.cache 0.17.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 392 kB
  • sloc: sh: 14; makefile: 2
file content (42 lines) | stat: -rw-r--r-- 921 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
library("R.cache")
oopts <- options("R.cache.compress")

simulate <- function(mean, sd) {
  # 1. Try to load cached data, if already generated
  key <- list(mean, sd)
  data <- loadCache(key)
  if (!is.null(data)) {
    cat("Loaded cached data\n")
    return(data)
  }

  # 2. If not available, generate it.
  cat("Generating data from scratch...")
  data <- rnorm(1000, mean=mean, sd=sd)
  Sys.sleep(1)             # Emulate slow algorithm
  cat("ok\n")
  saveCache(data, key=key, comment="simulate()")

  data
}


for (compress in c(FALSE, TRUE)) {
  options("R.cache.compress"=compress)

  data <- simulate(2.3, 3.0)
  data <- simulate(2.3, 3.5)
  data <- simulate(2.3, 3.0) # Will load cached data

  # Clean up
  file.remove(findCache(key=list(2.3,3.0)))
  file.remove(findCache(key=list(2.3,3.5)))
}


## Exceptions
res <- try(findCache(key = NULL))
stopifnot(inherits(res, "try-error"))

## Cleanup
options(oopts)