Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating LaTeX output from R data frame

Tags:

r

latex

sweave

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').

like image 358
Homunculus Reticulli Avatar asked Sep 03 '25 05:09

Homunculus Reticulli


2 Answers

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}
like image 193
Roman Luštrik Avatar answered Sep 04 '25 20:09

Roman Luštrik


Use kable() from knitr package to turn a dataframe into a LaTeX table from R. kableExtra package allows doing more fine-tuning.

# Toy example 
df <- tibble(x = c(1:3), 
             y = c(4:6))

# Plain latex output 
kable(df, "latex")

# With Booktabs 
kable(df, "latex", booktabs = TRUE)

# Using kableExtra 
df %>%
    kbl(caption = "Example", # Adding caption  
        format = "latex") %>% # Output format = latex 
    kable_classic(html_font = "Cambria") # Font = Cambria 
like image 25
jaeyeon Avatar answered Sep 04 '25 20:09

jaeyeon