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


% ----------------------------------
\documentclass{article} %


  \subsection{Patient #1}
  For patient #1, the mean value of systolic pressure was #2~mmHg, 
  the diastolic pressure was #3~mmHg.
      \caption{Histogram of systolic blood pressure for patient #1.}%
  \clearpage % Better use FloatBarrier here

\section{Blood Pressure}

dt = data.frame(subj=sample(1:3,n,TRUE),

# could also use tapply here
for (i in 1:3) {
  dt1 = dt[dt$subj==i,]
  hist(dt1$syst,main="",xlab="Blood pressure")


More information about the R-help mailing list