28.27 Referencing Chunks in LaTeX

REVIEW 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 (Xie 2023) to add an rcode environment around the chunks. The following chunk achieves this by adding some code to a hook function for knitr (Xie 2023). 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}\ {#%s}l{}', 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:

seq(0, 10, 2)
## [1]  0  2  4  6  8 10

We can then refer to the R code chunk with \@ref(demo_chunk_ref), which prints the R Code reference number as @ref(demo_chunk_ref), and \pageref{demo_chunk_ref}, which prints the page number as .

References

———. 2023. Knitr: A General-Purpose Package for Dynamic Report Generation in r. https://yihui.org/knitr/.


Your donation will support ongoing availability and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984. Copyright © 1995-2022 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0