交换缓存程序包 [英] Sweave Cache packages
问题描述
我正在尝试编织报告,而我的问题是,每次我编译R时,都会加载我在报告中使用的软件包(例如ggplot2,MASS,cubature ..).这非常耗时.有没有办法打包包裹?
I am trying to sweave a report and my problem is that every time i compile R loads the packages I use in the Report (like ggplot2, MASS, cubature..). This is very time consuming. Is there a way to chache the packages?
我找到了 cacheSweave ,但是它不起作用.
I found cacheSweave but it does not work.
这是我在sweave文件中添加的块:
This is the chunk i added in the sweave file:
<<cacheSweave, eval=TRUE, echo=FALSE, term=FALSE, cache=TRUE>>=
library(cacheSweave)
lapply(c("ghyp","MASS","nloptr","cubature","ggplot2"), require, character.only=T)
@
谢谢
推荐答案
由于您对knitr
软件包表现出了兴趣,因此我花了一些时间实施此功能,并且可以从
Since you showed interest in the knitr
package, I spent some time implementing this feature, and you can download the development version from https://github.com/yihui/knitr. As I said, cacheSweave
does not preserve any side effects; the current stable version of knitr
on CRAN only preserves the side effects of printing, and the side effects of loading packages are preserved in the development version (>= 0.3.3) on GitHub. When you run a cached chunk, all the package names are cached in a file __packages
. Next time when this chunk is to be rebuilt, all the packages will be loaded before executing the code in the chunk, otherwise this chunk will be skipped. In other words, packages are only loaded when they are really needed.
执行此操作的另一种方法是使用块挂钩,这不需要您安装开发版本.例如,您可以添加一个名为packages
的块选项,并设计一个块挂钩,例如:
The other way to do this is to use chunk hooks, which does not require you to install the development version. For example, you can add a chunk option named packages
, and design a chunk hook like:
<<setup, include=FALSE, cache=FALSE>>=
knit_hooks$set(packages = function(before, options, envir) {
if (before) {
## load packages before a chunk is executed
for (p in options$packages) library(p, character.only = TRUE)
}
})
@
然后您可以像这样使用此块选项
Then you can use this chunk option like
<<test, packages=c('MASS', 'ggplot2')>>=
qplot(rnorm(100))
@
其中选项packages
是包名称的字符向量,由上面定义的块挂钩使用.这种方法的缺点是您可能必须为许多块指定此packages
向量,而第一种方法是自动的.您可能需要花几分钟来学习knitr
中的块挂钩如何工作: http://yihui.name/针织衫/钩子
where the option packages
is a character vector of package names, which are used by the chunk hook defined above. The disadvantage of this approach is you may have to specify this packages
vector for many chunks, whereas the first approach is automatic. You may need to spend a few minutes on learning how chunk hooks work in knitr
: http://yihui.name/knitr/hooks
这篇关于交换缓存程序包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!