Go to TogaWare.com Home Page. Data Science Desktop Survival Guide
by Graham Williams
Duck Duck Go

Referencing Chunks in LaTeX

Raw We may like to reference code chunks from other parts of our document. LaTeX handles cross references nicely, and there are packages that extend this to user defined cross references. The amsthm package provides one such mechanism.

To add a cross referencing capability we can tell LaTeX to use the amsthm package and to create a new theorem environment called rcode by including the following in the document preamble (prior to the \begin{document}):

\usepackage{amsthm}
\newtheorem{rcode}{R Code}[section]

We then tell knitr to add an rcode environment around the chunks. The following chunk achieves this by adding some code to a hook function for knitr. This will typically also be in the preamble of the document, though not necessarily.

<<setup, include=FALSE>>=
knit_hooks$set(rcode=function(before, options, envir)
{
  if (before)
    sprintf('\begin{rcode}\label{%s}\hfill{}', options$label)
  else
    '\end{rcode}'
})
@

Once we've done that, we add rcode=TRUE for those chunks we wish to refer to. Here is a chunk as an example:

<<demo_chunk_ref, rcode=TRUE>>=
seq(0, 10, 2)
@

The output from the chunk is:


\begin{rcode}
\hfill{}
\begin{alltt}
\relax{} \textcolor[rgb]{0.737,0.353,0.396}...
...relax \end{alltt}\begin{verbatim}...

We can then refer to the R code chunk with \ref{demo_chunk_ref}, which prints the R Code reference number as 1, and \pageref{demo_chunk_ref}, which prints the page number as [*].


Support further development by purchasing the PDF version of the book.
Other online resources include the GNU/Linux Desktop Survival Guide.
Books available on Amazon include Data Mining with Rattle and Essentials of Data Science.
Popular open source software includes rattle and wajig.
Hosted by Togaware, a pioneer of free and open source software since 1984.
Copyright © 2000-2020 Togaware Pty Ltd. . Creative Commons ShareAlike V4.