Generating LaTeX output from R data frame

Homunculus Reticulli picture Homunculus Reticulli · Feb 14, 2012 · Viewed 31.2k times · Source

I am running R v2.14.1 on Ubuntu. I am writing a script that will generate a data frame, which represents a table of results.

I would like to output this 'table' as a .tex file so that I can create an 'academic publication' quality table, for printing. I have heard of Sweave (and read some overview docs about Sweave) - so I think this is the way to proceeed. However having said that I have not actually seen an example where Sweave outputs a dataframe as a tex file - all of the Sweave examples I have seen so far, seem contrived and not something that I can build upon.

Are there some guidelines I can follow, to output tex from a dataframe? Also, will it be simpler (more straight forward), if I built the TeX string directly from my R script and saved the string to file? (It is not clear to me, what Sweave offers over and above manually building the TeX string 'manually').

Answer

Roman Luštrik picture Roman Luštrik · Feb 14, 2012

The xtable package has some examples of how to generate tables - see vignette. When you're writing a chunk, make sure you set the chunk to <<results=tex>>. See Sweave example, for instance, this.

This is how I would output a data.frame.

<<results=tex>>
    xtable(my.data.frame)
@

And the raw result would looks something like this:

> xtable(my.data.frame)
% latex table generated in R 2.14.1 by xtable 1.6-0 package
% Tue Feb 14 10:03:03 2012
\begin{table}[ht]
\begin{center}
\begin{tabular}{rllr}
  \hline
 & p & q & r \\ 
  \hline
1 & condition\_a & grp\_1 &   3 \\ 
  2 & condition\_a & grp\_1 &   3 \\ 
  3 & condition\_a & grp\_1 &   4 \\ 
  4 & condition\_a & grp\_1 &   1 \\ 
  5 & condition\_b & grp\_1 &   4 \\ 
  6 & condition\_b & grp\_1 &   3 \\ 
  7 & condition\_b & grp\_1 &   5 \\ 
  8 & condition\_b & grp\_1 &   5 \\ 
  9 & condition\_a & grp\_2 &   4 \\ 
  10 & condition\_a & grp\_2 &   1 \\ 
  11 & condition\_a & grp\_2 &   1 \\ 
  12 & condition\_a & grp\_2 &   1 \\ 
  13 & condition\_b & grp\_2 &   5 \\ 
  14 & condition\_b & grp\_2 &   1 \\ 
  15 & condition\_b & grp\_2 &   5 \\ 
  16 & condition\_b & grp\_2 &   2 \\ 
   \hline
\end{tabular}
\end{center}
\end{table}