2

Is there a way to include the externaL code in the tangled file when I have:

<<xref>>=
@

(here xref is a reference to code in an external file)

or

<<internal-ref>>=
<<xref>>
@

Or do I need to source the external file and somehow work from that?

This is an issue when including knitr vignettes in packages. At the final stage of checking on a vignette, R tries to source the tangled file. Missing code causes problems!

I am using version 1.5 of knitr.

2 Answers2

1

The original design of purl() is flawed in many aspects. For example, it does not respect cross references using <<>>. I really do not think R CMD build/check should tangle the vignettes at all, since weaving has run the code once. That said, you can try the latest development version, in which I introduced a new function hook_purl() that should serve much better as the tangling utility. To enable it, use

knit_hooks$set(purl = hook_purl)

Then tangling is done during weaving time, which means whatever is executed is written to the R script. This guarantees the tangled R script really contains the code executed. You only need to call knit() once to get both the output document and the R script.

Yihui Xie
  • 28,913
  • 23
  • 193
  • 419
0

I am also using knitr version 1.5, and the second option you offered works fine for me.

Here, the only R code in the document is stored in a named unevaluated chunk in "child.Rnw":

<<xref, eval=FALSE, echo=FALSE, results="hide">>=
d <- 1:10
d
@

That file and its chunk are read into the main file, "main.Rnw", by an initial chunk that uses the child="filename" option. A second chunk evaluates the code:

\documentclass{article}
\begin{document}

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

<<internal-ref, eval=TRUE>>=
<<xref>>
@

\end{document}

It knits just fine, and more importantly, doing purl("main.Rnw") produces a tangled file "main.R" that includes all of the R code. "main.R" looks like this:

## ----child, child="child.Rnw", eval=TRUE---------------------------------

## ----xref, eval=FALSE, echo=FALSE, results="hide"------------------------
## d <- 1:10
## d


## ----internal-ref, eval=TRUE---------------------------------------------
d <- 1:10
d

I haven't tried running this as a vignette, but since it's not missing any of the source code, it looks it should at least solve your proximal problem...

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455