# NOT RUN {
# this example is based on \url{https://stackoverflow.com/a/41439691/1104685}
# create a temp directory for a and place a .Rmd file within
tmpdr <- paste0(tempdir(), "/llcache_eg")
dir.create(tmpdr)
old_wd <- getwd()
setwd(tmpdr)
cat("---",
"title: \"A Report\"",
"output: html_document",
"---",
"",
"```{r first-chunk, cache = TRUE}",
"mpg_by_wt_hp <- lm(mpg ~ wt + hp, data = mtcars)",
"x_is_pi <- pi",
"```",
"",
"```{r second-chunk, cache = TRUE}",
"mpg_by_wt_hp_am <- lm(mpg ~ wt + hp + am, data = mtcars)",
"x_is_e <- exp(1)",
"```",
sep = "\n",
file = paste0(tmpdr, "/report.Rmd"))
# knit the file. evaluate the chuncks in a new environment so we can compare
# the objects after loading the cache.
kenv <- new.env()
knitr::knit(input = paste0(tmpdr, "/report.Rmd"), envir = kenv)
# The objects defined in the .Rmd file are now in kenv
ls(envir = kenv)
# view the cache
list.files(path = tmpdr, recursive = TRUE)
# create another environment, and load only the second chunk
lenv <- new.env()
ls(envir = lenv)
lazyload_cache_labels(labels = "second-chunk",
path = paste0(tmpdr, "/cache"),
envir = lenv)
lenv$x_is_e
lenv$mpg_by_wt_hp_am
# load all the chuncks
menv <- new.env()
lazyload_cache_dir(path = paste0(tmpdr, "/cache"), envir = menv)
ls(envir = menv)
menv$x_is_pi
menv$x_is_e
# cleanup
setwd(old_wd)
unlink(tmpdr, recursive = TRUE)
# }
Run the code above in your browser using DataLab