Search code examples
rlatexsweave

Is it possible to make the \newcommand control sequence handle sweave code?


I use latex to write up homework assignments. I need to include both charts and R code with my assignment. Sweave has worked well for me so far, but I'd like to simplify common code blocks like this...

\begin{rcode}
<<label=sol1, include=FALSE>>=
plot(c(2,3,5,7,11))
@
\end{rcode}
\begin{figure}[H]
<<fig=TRUE,echo=FALSE>>=
<<sol1>>
@
\end{figure}

(Where rcode is just a custom float...the code goes at end of document, the chart is stationary.)

So something like this...

\chart{sol1}{plot(c(2,3,4,5,7,11))}

where \chart is defined by

\newcommand{\chart}[2]{
  \begin{rcode}
  <<label=#1, include=FALSE>>=
  #2
  @
  \end{rcode}
  \begin{figure}[H]
  <<fig=TRUE,echo=FALSE>>=
  <<#1>>
  @
  \end{figure}
}

Sadly, it appears that sweave gets to the source code before latex processes \newcommand, and so this approach doesn't work. Is there a way to tweak how the source is processed so that the macros are dealt with before sweave sees the source? Or is there a better approach to this kind of problem?

Thanks in advance for any suggestions..


Solution

  • I hope the following is about what you wanted to solve the hen/egg problem. I have stolen it from my own post on the R-list

    % ---------------------------------- 
    \documentclass{article} %
    \usepackage{Sweave} 
    \SweaveOpts{echo=FALSE}
    
    \newcommand\bloodp[3]{
      \subsection{Patient #1} For patient #1, the mean value of systolic pressure was #2~mmHg, the diastolic pressure was #3~mmHg. 
      \begin{figure}[!htb]% 
        \begin{center}% 
          \includegraphics{histo#1}%
          \caption{Histogram of systolic blood pressure for patient #1.}% 
          \label{fig:histo#1}% 
        \end{center}% 
      \end{figure}% 
      \clearpage % Better use FloatBarrier here 
    }
    
    \begin{document} 
    \section{Blood Pressure}
    
    <<results=tex>>= 
    n=100 
    dt = data.frame(
       subj=sample(1:3,n,TRUE), 
       syst=round(rnorm(n,120,10)),
       dia=round(rnorm(n,80,10))
       )
    # could also use tapply here 
    for (i in 1:3) { 
      dt1 = dt[dt$subj==i,] 
      cat("\\bloodp{",i,"}{", 
         round(mean(dt1$syst)),"}{", 
         round(mean(dt1$dia)),"}\n",sep="") 
       pdf(paste("histo",i,".pdf",sep="")) 
       hist(dt1$syst,main="",xlab="Blood pressure") 
       dev.off() } 
    @
    
    \end{document}