Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching child files in knitr

I have a problem with child files in knitr. The caching works fine, but the dependencies do not work. My sandbox example looks like that:

\documentclass{article}

\begin{document}

<<setup, cache=FALSE>>=
opts_chunk$set(cache=TRUE, autodep=TRUE)
dep_auto() # figure out dependencies automatically
@

<<a>>=
x <- 14
@

<<b>>=
print(x)
@

<<child, child='child.Rnw', eval=TRUE>>=
@

\end{document}

With the 'child.Rnw' looking like this:

<<child>>=
print(x)
@

When I now compile the code, then change x in chunk a and then compile it again: chunk b reacts properly, but the child does not. Am I doing something obviously wrong?

Thanks for the help!

like image 265
panuffel Avatar asked Feb 26 '13 16:02

panuffel


People also ask

What does clear knitr cache do?

I finally realized that if I use the knitr dropdown to clear the knitr cache, it clears the rsession memory.

How do I use cache in R markdown?

R Markdown has a built-in caching feature that can be enabled by setting cache=TRUE in the chunk's header. The second time the chunk is run, both the visual output and any objects created are loaded from disk.

What is the purpose of knitr?

knitr is an engine for dynamic report generation with R. It is a package in the programming language R that enables integration of R code into LaTeX, LyX, HTML, Markdown, AsciiDoc, and reStructuredText documents. The purpose of knitr is to allow reproducible research in R through the means of literate programming.

What is knitr RMarkdown?

RMarkdown is an extension to markdown which includes the ability to embed code chunks and several other extensions useful for writing technical reports. The rmarkdown package extends the knitr package to, in one step, allow conversion between an RMarkdown file (.Rmd) into PDF, HTML, word document, amongst others.


1 Answers

I thought for a while about this issue, and I find it difficult to fix at the moment. The problem is that the parent document does not really know what is in the child document, and dep_auto() does not take the child documents into account when setting the dependency structure. There are two ways to solve this problem. The first one is hackish:

knitr:::dep_list$set(a = c('child', 'b'))

As you probably know, ::: means "danger zone" in R. In knitr, dep_list is the internal object that controls the dependency structure. Both dep_auto() and dep_prev() rely on this object (similarly that is how the chunk option dependson works).

The second way is to write your object into chunk options, e.g.

<<child, whatever=x>>=
print(x)
@

Read the third section in the knitr cache page for details.

like image 102
Yihui Xie Avatar answered Sep 29 '22 17:09

Yihui Xie