6

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?

4

1 回答 1

7

是的,您可以制作var部分块选项,例如

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

cache.whatever不是官方的 chunk 选项名称,但是你可以在 中使用任意选项knitr,它们会影响缓存失效。在这种情况下,当var被更新时,缓存将被更新。

如果要var影响所有缓存的块,可以将其设置为全局选项,但请记住将其设置为未计算的表达式:

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

您可以在内部使用任意 R 表达式quote(),因此如果您有更多变量,可以将它们放在一个列表中,例如

opts_chunk$set(cache.whatever = quote(list(var1, var2)))
于 2013-08-23T04:36:09.110 回答