Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show code in appendix using knitr

Tags:

r

knitr

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?

like image 292
DavidC Avatar asked Aug 22 '13 07:08

DavidC


People also ask

How do you put an appendix code in LaTeX?

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} .

How do I embed an R code in Markdown?

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.

How do you use knitr in R?

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.


1 Answers

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 purling, stitching the purled code, knitting the original document, and then compiling the resulting LaTeX ("example.tex") that includes the knitting and purling. Everything should be formatted nicely (and consistently).

like image 59
Thomas Avatar answered Oct 19 '22 21:10

Thomas