Cache Code Chunks with knitr

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:

```{r cachedChunk, cache=TRUE}
# This chunk will cache its results and
# only re-evaluate when changes are present.

# Sort columns of a random 10,000 x 10,000 matrix
foo <- matrix(rnorm(100000000), 10000, 10000)
system.time(bar <- apply(foo, 2, sort))
```

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. For more details, see the cache section of the knitr documentation. For examples of other other knitr options, see Customizing Chunk Options in R Markdown.