[Tex/LaTex] How use LaTeX counters to label knitr code chunks

cross-referencingknitrr

Imagine one has the LaTeX environments Example and Solution defined from the theorem environment. I have several Examples in numerous child documents which make up a book. LaTeX will automagically track the chapter and Example, Solution, Figure, etc number for a labeled Example, Solution, Figure, etc., respectively. Suppose the first code chunk below corresponds to the 6th Example in Chapter 4 of a book. Then \ref{SetSeed} will return the number 4.6 when using \documentclass{book}. I would like to be able to provide names to my code chunks that will stay in synchronization with the labels of my different LaTeX environments (Example, Solution, Figure, etc.). What I do not want to do is hard code my code chunks with 'Example 4.6', etc. Any suggestions would be most welcome. I am aware of the code chunk options Yihui has for figure captions and labels but would be willing to do an "old style" code chunk surrounded with a \begin{figure}, \end{figure} environment if the code chunks can be named appropriately. The thought is that the named code chunk might be generated with something like

<<paste(Solution,'\ref{SetSeed}', sep=" "), echo = TRUE>>=    ...(which does not work) 

to generate the named chunk 'Solution 4.6'. The rationale is to be able to later purl() the master document to produce labeled code chunks from the individual chapters that correspond to the environments (Figure, Example, Solution, etc.) displayed in the book. Thanks in advance, Alan.

\begin{Example} \label{SetSeed}
Use the function \texttt{set.seed()} with a value of 13 and generate 
20 values from a normal distribution with a mean of 100 and a standard 
deviation of 15.  Find the mean of the randomly generated values.
\end{Example}

\begin{Solution}  
<<paste(Solution,'\ref{SetSeed}', sep=" "), echo = TRUE>>=
# some R code
set.seed(13)
xs <- rnorm(20, 100, 15)
@
The mean of the values generated in Example \ref{SetSeed} have a 
mean of \Sexpr{mean(xs)}.
\end{Solution}

Best Answer

That is a challenging problem. As Ben Bolker pointed out, it is a one-way flow: when R is done, nothing will come back from LaTeX to R again, so R will not be able to know the value of \ref{SetSeed} in LaTeX.

However, I do not think it is completely impossible, because you actually have the *.aux file generated from LaTeX, which you can parse with R for the solution numbers, and update the raw R script from purl() with this information. One approach is that you use the same label for the R chunk as you used for the Example environment, and you will get a code chunk in the output like:

## @knitr SetSeed
# R code

Hopefully you will also see this in the *.aux file after you have run LaTeX on the *.tex file:

\newlabel{SetSeed}{{1}{1}}

Then you replace SetSeed in the R code with Solution 1.1. In all, you need some post-processing of the R script.