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

From: Dieter Menne <>
Date: Sat, 14 Jun 2008 07:30:04 +0000 (UTC)

Stephan Kolassa <Stephan.Kolassa <at>> 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/ 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")

\end{document} mailing list PLEASE do read the posting guide and provide commented, minimal, self-contained, reproducible code. Received on Sat 14 Jun 2008 - 07:33:47 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 14 Jun 2008 - 10:30:42 GMT.

Mailing list information is available at Please read the posting guide before posting to the list.

list of date sections of archive