Invalidate a chunk's cache when uncached chunk changes

孤人 提交于 2019-12-19 07:25:07

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/18376008/invalidate-a-chunks-cache-when-uncached-chunk-changes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!