tl;博士
我的问题:在 R 会话中,是否有某种方法可以使用knitr的缓存结果“快进”到给定代码块中可用的环境(即对象集),就像它knit()
本身一样?
设置:
knitr内置的代码块缓存是其杀手级功能之一。
当某些块包含耗时的计算时,它特别有用。除非它们(或它们所依赖的块)被更改,否则只需要在第一次knit
编辑文档时执行计算:在所有后续调用 时knit
,块创建的对象只会从缓存中加载。
这是一个最小的示例,一个名为的文件"lotsOfComps.Rnw"
:
\documentclass{article}
\begin{document}
The calculations in this chunk take a looooong time.
<<slowChunk, cache=TRUE>>=
Sys.sleep(30) ## Stands in for some time-consuming computation
x <- sample(1:10, size=2)
@
I wish I could `fast-forward' to this chunk, to view the cached value of
\texttt{x}
<<interestingChunk>>=
y <- prod(x)^2
y
@
\end{document}
编织和 TeXify 所需的时间"lotsOfComps.Rnw"
:
## First time
system.time(knit2pdf("lotsOfComps.Rnw"))
## user system elapsed
## 0.07 0.02 31.81
## Second (and subsequent) runs
system.time(knit2pdf("lotsOfComps.Rnw"))
## user system elapsed
## 0.03 0.02 1.28
我的问题:
在 R 会话中,是否有某种方法可以使用knitr的缓存结果“快进”到给定代码块中可用的环境(即对象集),就像它knit()
本身一样?
执行purl("lotsOfComps.Rnw")
然后运行代码"lotsOfComps.R"
是行不通的,因为沿途的所有对象都必须重新计算。
理想情况下,可以做这样的事情来结束在开头存在的环境中<<interestingChunk>>=
:
spin("lotsOfComps.Rnw", chunk="interestingChunk")
ls()
# [1] "x"
x
# [1] 3 8
既然spin()
(还没有?)可用,那么获得等效结果的最佳方法是什么?