Smich7 Smich7 - 4 months ago 10
LaTeX Question

Eval LaTeX code in R chunk (Knitr)

I'm actually creating a shiny app. In that app, there is a download button which download a PDF file that depends of user's input.

So I use a

.rnw
file to do generate that PDF document. I just want to do a table (with tabular) which have a number of row that depends of app user's input.

So in my R chunck, i'd like to do something like that :

\begin{tabular}{c|c}

<<echo=FALSE>>=
for (index in 1:nrow(myData))
{
SomethingThatRunLaTeXCode(paste0("\hline ",
"\Sexpr{",myData[index,1],"}"," % ","\Sexpr{",myData[index,2],"}"))
}
\hline
\end{tabular}
@

Answer

As suggested by sebastian-c, a much better way to make such a table is to use the xtable package together with Knitr. To make the Knitr chunks understand TeX, use the chunk option results='asis'.

Since your data is a data.frame, it is straight-forward:

<<echo = FALSE, results = "asis">>= 

## test data
set.seed(1)
df <- data.frame(Gaussian = rnorm(10), Exponential = rexp(10))

library(xtable)
cap = paste("My caption can span multiple lines and",
            "can be arbitrarily long.")
xtable(df,caption = cap)
@

For full customization, use the function print.xtable on your xtable object.

<<echo = FALSE, results = "asis">>=
print.xtable(xtable(df),table.placement = "")
@
Comments