[Tex/LaTex] How to loop over R objects OUT OF chunks

knitrloopsrsweave

I want to typeset with TeX a report based on data from an R object (dataframe). The idea is to print a nice TeX table from each line of a R dataframe.

Something like

\begin{tabular}{ l c r }
   A1 & B1 & C1  \\
\end{tabular}

\begin{tabular}{ l c r }
   A2 & B2 & C2  \\
\end{tabular}

\begin{tabular}{ l c r }
   A3 & B3 & C3  \\
\end{tabular}

Please consider the following MWE

\documentclass{article}

\begin{document}

<<prepare data>>=
one   <- c("A1","B1","C1")
two   <- c("A2","B2","C2")
three <- c("A3","B3","C3")
df <- data.frame(one,two,three)
@

<<loop data>>=
for (i in 1:nrow(df)) {
  print(df[i])
}
@

\end{document}

which produces

enter image description here

How could I typeset the values outputted by the R loop with TeX? In other words, how to \loop...\repeat with TeX over R loop variables.

Best Answer

You can use the xtable package:

<<loop-data, results='asis'>>=
library(xtable)
for (i in 1:nrow(df)) {
  print(xtable(t(df[i])))
}
@

Or use the kable() function in knitr:

<<loop-data, results='asis'>>=
for (i in 1:nrow(df)) {
  kable(t(df[i]), row.names=FALSE)
}
@

kable() in knitr

The key is the chunk option results='asis'.