# r - Invalidate a chunk's cache when uncached chunk changes

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_cachedvar <- 42## @knitr cachedvar

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?

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)))