title: Dynamic references to figures in a R comment within Sweave document
body: <p>I would like to find a way to use the LaTeX <code>\ref{}</code> markup to comment in the R code within a Sweave .Rnw file.  Here are two examples, one in print</p>
  
  <p><a href="http://cm.bell-labs.com/cm/ms/departments/sia/project/nlme/UGuide.pdf" rel="nofollow">http://cm.bell-labs.com/cm/ms/departments/sia/project/nlme/UGuide.pdf</a></p>
  
  <p>and one to use to work with:</p>
  
  <p>The .Rnw file</p>
  
  <pre><code>% File: example.Rnw
  
  \documentclass{article}
  \usepackage{fullpage}
  \usepackage{graphics}
  \usepackage{Sweave} 
  \usepackage[margin = 10pt, font=small, labelfont={bf}]{caption}
  
  \begin{document}
  
  Here is an example file to show what I want to do.  I would like to figure out how to use the \LaTeX\ reference command to reference a figure being generated by R code.  Note in the R code, in a comment there is a reference to the figure, but of course the output file shows a verbatim copy of the \LaTeX\ markup.  Does anyone know how to get something for Figure \ref{fig2}?
  
  &lt;&lt; example plot &gt;&gt;=
  library(reshape)
  library(ggplot2)
  
  n &lt;- 100
  lambda &lt;- 1 / 3 
  x &lt;- seq(0, qexp(0.999, rate = lambda), length = n)
  q1.a &lt;- data.frame(x =   x,
                     f =   dexp(x, rate = lambda),
                     F =   pexp(x, rate = lambda))
  
  q1.a &lt;- melt(q1.a, id.vars = 'x')
  g &lt;- ggplot(q1.a) +                                     # Produces \ref{fig1} 
         aes(x = x, y = value) + 
         geom_line() + 
         facet_wrap( ~ variable, scale = "free_y")
  ggsave(g, filename = "example1.jpeg")                    
  @
  
  \begin{figure}[h]
  \centering
  \includegraphics[width = 0.48\textwidth]{./example1}
  \caption{Exponential Distribution based plots.}
  \label{fig1}
  \end{figure}
  
  Here is more of what I would like to see:
  
  &lt;&lt; example plot 2 &gt;&gt;=
  ggsave(g + geom_point(), filename = "example2.jpeg")    # Produces Figure 2
  @
  
  \begin{figure}
  \centering
  \includegraphics[width = 0.48\textwidth]{./example2}
  \caption{Exponential Distribution based plots with points and lines.}
  \label{fig2}
  \end{figure}
  
  \end{document}
  </code></pre>
  
  <p>and the pdf is build with the R commands</p>
  
  <pre><code>Sweave(file = 'example.Rnw',
         engine = "R",
         keep.source = 'TRUE',
         echo = 'TRUE',
         results = 'verbatim')
  
  tools::texi2dvi(file  = "example.tex",
                  pdf   = TRUE,
                  clean = TRUE)
  </code></pre>
  
  <p>Any insight on how do this would be great.</p>