[Tex/LaTex] Supplying string parameters to Sweave document

graphicsparameterssweave

This must be a simple question but I don't figure out how I can do it.

I would like to produce a pdf report using Sweave. And actually, many many reports.

I shortened and simplified the sweave code to get to the point. Here's the code (short.rnw) :

\documentclass[a4paper,11pt]{article}
\usepackage[latin1]{inputenc}
\usepackage[OT1]{fontenc}
\usepackage{graphicx}
\usepackage{Sweave}

\begin{document}  
\section*{MySection}  

\begin{figure}[htbp]
\caption*{MyCaption}
<<echo=FALSE,results=tex>>=
file=paste(getwd(),"fig","boxp.png",sep="/")
cat("\\includegraphics[width=0.5\\textwidth]{",file,"}",sep="")
@
\end{figure}

\end{document}

As you can see, this code simply includes a graphic named "boxp.png" in the report. I actually don't need sweave to do this but what I really want to do is to generate multiple reports with a varying filename.

So, is there a way to pass a string parameter (or any kind of parameter) to build the report without having to rewrite the sweave template each time ?

I generate the reports from a bash script with the command 'R CMD Sweave short.rnw', the string parameters being defined before this call.

EDIT :

#!/bin/bash

for f in ${files}
do

prog1 f 
# prog1 is a program which generates figures in a directory dir
# this directory has a name depending on f name
# for instance if f="foo.txt", then dir="./foo_dir"

###
#And now HERE I have to create my report with the images
#in foo_dir
# And I don't know how I can specify the varying names of dir
# in my template...

done

Thanks.

Tony

Best Answer

there are two ways to do what you seek. one is using sweave, the other is using an R package called brew which overcomes sweave's limitations of looping over a global variable. i am providing both code chunks.

The Sweave Code Chunk

\begin{document}
<<echo = F, results = tex>>=

figdir   = paste(getwd(), 'fig', sep = '/')
fignames = read.csv('fignames.csv');
for (i in seq_along(fignames)) {

 filename = file.path(figdir, i)

 cat("\\pagebreak");
 cat("\\section{", i, "}", sep = "");
 cat("\\begin{figure}[htbp]");
 cat("\\caption*{MyCaption", i, "}", sep = "");
 cat("\\includegraphics[width = 0.5\\textwidth]{", filename, "}", sep = "");
 cat("\\end{figure}");
}
@

\end{document}

The Brew Code Chunk

\begin{document}
<% figdir   = paste(getwd(), 'fig', sep = '/') %> 
<% fignames = read.csv('fignames.csv');
<% for (i in seq_along(fignames)) { -%>

\pagebreak

<% filename = file.path(figdir, i) %>  
<%= cat("\section{", i, "}", sep = "") %>

\begin{figure}[htbp]
\caption*{MyCaption}

<%= cat("\\includegraphics[width = 0.5\\textwidth]{filename}")

\end{figure}
<% } -%>
\end{document}

you can check out the link to brew on how to use it from R

EDIT: this would produce a single file with all the output.