简体   繁体   中英

How to cache knitr chunks across two (or more) files?

I want to use some R-Code in two different *.Rnw files and want to use caching across those files. I read http://yihui.name/knitr/demo/externalization/

Caching in one file just works fine. But running the second one the whole code is executed again:

plain.R

## @knitr random1
a <- rnorm(10)
a

doc1.Rnw (and doc2.Rnw)

\documentclass{article}

<<set-options, echo=FALSE, cache=FALSE>>=
 options(replace.assign=TRUE)
 opts_chunk$set(external=TRUE, cache=TRUE, echo=FALSE, fig=TRUE)
 read_chunk('plain.R')
@

\title{Doc 1}

\begin{document}

<<random1>>=
@

\end{document}

Is there a way to share the cache across several documents?

It is entirely possible to reuse the cache across multiple source documents. Please read the cache page carefully to understand when cache will be rebuilt. In your case, the cache is not supposed to be rebuilt unless your two documents have different chunk options (condition 1), or different getOption('width') (condition 3), since your code remains the same (condition 2).

You have to post a reproducible example, otherwise this is not considered a real question.

After completely resetting the example it turned out that the cache is reused by both files. I'm not sure what caused the problem before ....

But in a bigger project the chunks are not cached. So I'm not sure what causes the problem - maybe just a different count of spaces ....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM