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

时间:2021-08-22 20:45:03

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?

我有一个关于knitr chunk选项“dependson”的问题。据我所知,手册此选项应该用于指定缓存块所依赖的其他缓存块。但有没有办法在未缓存的块更改时使块的缓存无效?

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.

当我更改var时,块“缓存”的输出仍为42,因为dependson选项不适用。在我的例子中,我也可以通过缓存第一个块来解决问题。但是,我不能这样做,因为在第一个块中我使用library()并读入外部文件,因此不应缓存此块。

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

有没有办法在未缓存的块更改时使缓存无效?

1 个解决方案

#1


6  

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

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

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

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

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

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.

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

opts_chunk$set(cache.whatever = quote(list(var1, var2)))

#1


6  

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

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

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

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

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

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.

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

opts_chunk$set(cache.whatever = quote(list(var1, var2)))