Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalidate a chunk's cache when uncached chunk changes

Tags:

r

knitr

I have a question regarding the knitr chunk option "dependson". As far as I understood the manual this option should be used to specify which other cached chunks a cached chunk depends on. But is there a way to invalidate a chunk's cache when an uncached chunk changes?

Here's a minimal example:

File knitrtest.Rnw:

\documentclass{article}
\begin{document}

<<>>=
library(knitr)

read_chunk("chunks.R")
@

<<not_cached>>=
@

<<cached, cache=TRUE, dependson="not_cached">>=
@

\end{document}

File chunks.R:

## @knitr not_cached
var <- 42

## @knitr cached
var

When I change var the output from chunk "cached" is still 42 as the dependson option doesn't apply. In my example I could solve the problem by caching the first chunk, too. However, I cannot do that because in the first chunk I use library() and read in external files, so this chunk should not be cached.

Is there a way to invalidate cache when a not cached chunk changes?

like image 290
CL. Avatar asked Aug 22 '13 09:08

CL.


1 Answers

Yes, you can make var a part of the chunk options, e.g.

<<cached, cache=TRUE, cache.whatever=var>>=
@

cache.whatever is not an official chunk option name, but you can use arbitrary options in knitr, and they will affect the cache invalidation. In this case, when var is updated, the cache will be updated.

If you want var to affect all cached chunks, you can set it as a global option, but remember to set it as an unevaluated expression:

opts_chunk$set(cache.whatever = quote(var))

You can use arbitrary R expressions inside quote(), so if you have more variables, you can put them in a list, e.g.

opts_chunk$set(cache.whatever = quote(list(var1, var2)))
like image 114
Yihui Xie Avatar answered Nov 08 '22 06:11

Yihui Xie