I have an Rnw file (a large one) and I want to show all code used in an appendix.
It is suggested in some of the knitr examples (https://github.com/yihui/knitr-examples/blob/master/073-code-appendix.Rnw, also a good MWE) that having a code block like this is the way:
<<Rcode, eval=FALSE, ref.label=all_labels()[-1],echo=TRUE, cache=FALSE>>=
@
This works fine except all the code chunks merge into each other and none are labelled.
On the other hand if I run purl(myfile.Rnw) it labels the code chunks and separates them by two lines, which makes things much easier to read.
Is there any way of automatically listing the code using the second approach in a report appendix? I know I can have a code chunk to run purl to produce myfile.R as part of my report, but how do I then show the code in myfile.R in my appendix?
How do you make an appendix in LaTeX? Referencing an appendix in LaTeX is as easy as any other chapter or object. You just have to put an anchor to it using \label{name} and then you can reference the appendix using \ref{name} .
To insert a code chunk, press Ctrl + Alt + I in the source pane (top left pane in the default settings of RStudio). A code chunk will appear: Inside the code chunk you can write and run R-code.
There are two ways to render an R Markdown document into its final output format. If you are using RStudio, then the “Knit” button (Ctrl+Shift+K) will render the document and display a preview of it. Note that both methods use the same mechanism; RStudio's “Knit” button calls rmarkdown::render() under the hood.
Here's an example .Rnw file (called "example.rnw"):
\documentclass{article}
\begin{document}
<<a>>=
x <- 1:10
x
@
<<b>>=
y <- 10:1
y
@
<<c>>=
z <- 1:5
z
@
\clearpage
\input{example-purl.tex}
\end{document}
If you create a file in your working directory called "template.rnw" that just contains:
<<%sCHUNK_LABEL_HERE, eval=FALSE>>=
@
Then, you run:
stitch(purl("example.rnw",output="example-purl.r"),template="template.rnw")
knit("example.rnw")
Does that make sense? Basically, you're purl
ing, stitch
ing the purl
ed code, knit
ting the original document, and then compiling the resulting LaTeX ("example.tex") that includes the knit
ting and purl
ing. Everything should be formatted nicely (and consistently).
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