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?
I found cacheSweave but it does not work.
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)
@
Thanks
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.
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))
@
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
You don't call library(cacheSweave)
in your Sweave (rnw) file. Consider the following test.rnw
file:
\documentclass{article}
<<cachedCode,cache=TRUE>>=
#this Sweave block will be cached
@
\begin{document}
\end{document}
Then you would run this using:
require(cacheSweave)
Sweave('test.rnw', driver=cacheSweaveDriver)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With