João Daniel
João Daniel

Reputation: 8986

Dynamic Sweave document

Is it possible to generate a LaTeX document through Sweave that don't have the number of its elements predefined? I mean, suppose I need to build a table for each row in a dataframe. The number of tables in the document will depend on the number of rows in the dataframe.

In other words, generate LaTeX elements inside a for loop. For each row Sweave would build a table.

The same would apply for pages, or other elements. Is it possible to do this?

Upvotes: 3

Views: 407

Answers (2)

vaettchen
vaettchen

Reputation: 7659

Does this help:

\documentclass[a4paper,12pt]{article}
\usepackage{Sweave}

\begin{document}

<<echo=FALSE>>=
library( xtable )
df <- structure(list(ID = 2:6, home_pc = structure(c(2L, 6L, 1L, 3L,
5L), .Label = c("BY5 8IB", "CB4 2DT", "DH4 6PB", "KN4 5GH", "MP9 7GH",
"NE5 7TH", "VB2 4RF"), class = "factor"), start_pc = structure(c(4L,
3L, 4L, 2L, 1L), .Label = c("BV6 5PB", "CB3 5TH", "FC5 7YH",
"Home", "NA"), class = "factor"), end_pc = structure(c(1L, 3L,
3L, 3L, 2L), .Label = c("CB5 4FG", "GH6 8HG", "Home", "NA"), class = "factor")), .Names = c("ID",
"home_pc", "start_pc", "end_pc"), row.names = 2:6, class = "data.frame")
count = 1
end = 3
@

<<fun,echo=FALSE,eval=FALSE>>=
print( xtable( df ) )
@


<<echo=FALSE,results=tex>>=
for( i in 1:end )
{
    print( xtable( df ) )
    i <- i + 1
}
cat( "\\newpage" )
@

<<echo=FALSE,results=tex>>=
if( count < end )
<<fun>>
count = count + 1
cat( "\\newpage" )
@

<<echo=FALSE,results=tex>>=
if( count < end )
<<fun>>
count = count + 1
cat( "\\newpage" )
@

<<echo=FALSE,results=tex>>=
if( count < end )
<<fun>>
count = count + 1
cat( "\\newpage" )
@

\end{document}

Happy to go into more details if this is the right track!

Upvotes: 2

Ramnath
Ramnath

Reputation: 55695

Here is a shorter way to do the same. I am using the mtcars dataset in R and will illustrate how to create tables by number of cylinders. You can process this document using Sweave or knitr (which is the new kid on the block). Let me know how it works.

\documentclass{article}
%\SweaveOpts{echo = F}

\begin{document}
<<load-libraries>>=
suppressMessages(require(plyr))
suppressMessages(require(xtable))
@

<<gen-tables, results = tex>>=
d_ply(mtcars, .(cyl), xtable, .print = TRUE)
@

\end{document}

Upvotes: 0

Related Questions