Data Science Desktop Survival Guide by Graham Williams Desktop Survival Project Home Preface Data Science Introducing R R Constructs R Tasks R Strings R Read, Write, and Create Data Template Data Exploration Data Wrangling Data Visualisation Statistics ML Template ML Scenarios ML Activities ML Applications ML Algorithms Cluster Analysis Decision Trees Computer Vision Graph Data Privacy Literate Data Science Coding with Style Resources Bibliography Index

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

 <>= 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:

 <>= seq(0, 10, 2) @ 

The output from the chunk is:

 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 .