为什么不应该重建高速缓存?

时间:2019-04-27 17:18:15

标签: r knitr

一个最小的示例如下:

\documentclass{article}

<<setup, echo = FALSE>>=
knitr::opts_chunk$set(
  cache = TRUE,
  autodep = TRUE
)
@

\begin{document}
<<chunk1>>=
n <- 6
rnorm(n)
@

<<chunk2>>=
n <- 10
rnorm(n)
@

\end{document}

运行一次代码,将结果缓存。当我更改第一个块中的代码时,说n <- 10并重新运行代码,则块2也将重新构建。我希望chunk2不会被重建,因为它不应该依赖于第一个chunk中的n


在上面的示例中,我使用了rnorm。如@ m0nhawk所述,这两个块是间接相关的。以下代码不涉及随机。问题依旧。

\documentclass{article}

<<setup, echo = FALSE>>=
knitr::opts_chunk$set(
  cache = TRUE,
  autodep = TRUE
)
@

\begin{document}
<<chunk1>>=
n <- 6
print(seq_len(n))
print(Sys.time())
@

<<chunk2>>=
n <- 10
print(seq_len(n))
print(Sys.time())
@


\end{document}

2 个答案:

答案 0 :(得分:0)

这两个大块由.Random.seed间接关联。

knitr支持保存random seed,但不能直接使用。

要使其正常运行,请将rand_seed添加到opts_chunk并为每个块设置不同的种子:

\documentclass{article}

<<setup, echo = FALSE>>=
knitr::opts_chunk$set(
  cache = TRUE,
  autodep = TRUE,
  cache.extra = rand_seed
)
@

\begin{document}
\SweaveOpts{concordance=TRUE}
<<chunk1>>=
set.seed(100)
n <- 10
rnorm(n)
@

<<chunk2>>=
set.seed(101)
n <- 10
rnorm(n)
@
\end{document}

答案 1 :(得分:0)

我认为这是a bug of knitr,我刚刚在Github上按下了a fix。发生此事件是因为尝试修复another related issue。再次考虑,我认为您报告的问题应优先考虑,因此在清除cache/目录并安装 knitr 的开发版本之后,您的示例应该可以正常工作: / p>

remotes::install_github('yihui/knitr')
相关问题