当未缓存的块发生更改时,使块的缓存无效

问题描述:

我有一个关于编织块选项"dependson"的问题.据我所理解的手册,应该使用该选项来指定一个缓存块依赖于哪些其他缓存块.但是当未缓存的块发生变化时,是否有一种方法可以使块的缓存无效?

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?

这是一个最小的例子:

文件 knitrtest.Rnw :

\documentclass{article}
\begin{document}

<<>>=
library(knitr)

read_chunk("chunks.R")
@

<<not_cached>>=
@

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

\end{document}

文件 chunks.R :

## @knitr not_cached
var <- 42

## @knitr cached
var

当我更改 var 时,由于依赖选项不适用,块"cached"的输出仍为42. 在我的示例中,我也可以通过缓存第一个块来解决该问题.但是,我不能这样做,因为在第一个块中,我使用library()并读取外部文件,因此不应缓存该块.

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?

是的,您可以使var成为块选项的一部分,例如

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

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

cache.whatever不是官方的块选项名称,但是您可以在knitr中使用任意选项,它们将影响缓存失效.在这种情况下,当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.

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

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

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

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