To compile your document faster, specified code chunks can be cached. This allows compute intensive chunks to be saved and the output used later without being rerun. To cache a chunk in knitr, simply use the
cache=TRUE option as shown here:
The knitr package is elegantly designed to only evaluate cached chunks when necessary. It creates a unique MD5 digest of each chunk to track when changes are present. When
cache=TRUE, the chunk will only be evaluated in the following scenarios:
The cached results and output are stored in a
cache/ directory relative to the current working directory. This directory can be customized with the
cache.path optoin. The full details of each option are copied below:
FALSE; logical) whether to cache a code chunk; when evaluating code chunks, the cached chunks are skipped, but the objects created in these chunks are (
lazy-) loaded from previously saved databases (
.rdx) files, and these files are saved when a chunk is evaluated for the first time, or when cached files are not found (e.g. you may have removed them by hand); note the filename consists of the chunk label with an MD5 digest of the R code in the chunk (the MD5 string is a summary of the chunk text, and any changes in the chunk will produce a different MD5 digest); unlike the cacheSweave package which uses stashR, this package directly uses internal functions in base R for cache, and another difference is that results of the code will still be included in the output even when cache is used (whereas cacheSweave has no output when a chunk is cached), because knitr also caches the printed output of a code chunk as a character string.
'cache/'; character) a prefix to be used for the names of cache files (by default they are saved to a directory named cache relative to the current working directory; you can also use an absolute dir here, e.g.
/home/foo/bar- or D:
\\abc\\mycache, but it is not recommended since such absolute directories may not exist in other people's systems, therefore it is recommended to use relative directories)
NULL; character) a character vector of chunk labels to specify which other chunks this chunk depends on; this option applies to cached chunks only – sometimes the objects in a cached chunk may depend on other cached chunks, so when other chunks are changed, this chunk must be updated accordingly
FALSE; logical) whether to figure out the dependencies among chunks automatically by analyzing the global variables in the code (may not be reliable) so that
dependson does not need to be set explicitly
For additional information and examples, see the cache section of the knitr documentation.
Return to Using Markdown with RStudio