[R] Sweave: looping over mixed R/LaTeX code

Dieter Menne dieter.menne at menne-biomed.de
Sat Jun 14 09:30:04 CEST 2008


Stephan Kolassa <Stephan.Kolassa <at> gmx.de> writes:

> 
> I would like to loop over a medium amount of Sweave code, including both R 
and LaTeX chunks. Is there any way to

Stephan noted that \newcommand was not expanded, so after re-reading I 
realized that my comment was a bit short. After all, when I had encountered 
the problem the first time, I remember some headaches when thinking about 
the hen and the egg.

Below is a full example. The trick is to generate the newcommand and 
parameter with R. This method is especially helpful when you have a dozen or 
so of laboratory parameter that all have to be plotted, tabled, tested 
between groups, and summarized. I write the chapter only once, when I works 
I wrap everything with a newcommand. Default Sweave figure creation is 
not possible, but doing it explicitely with a pdf/dev.off is not much 
more complicated.


Dieter

% ----------------------------------
\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}



More information about the R-help mailing list