how to export a dataframe to latex with some minimal formatting?

2.6k views Asked by At

Consider this simple example

library(dplyr)
dataframe <- data_frame(mytext1 = c('HELLO',
                                   'WORLD'),
                        mytext2 = c('HELLO',
                                   'AGAIN'),
                        value1 = c(1,2), 
                        value2 = c(1,2))

# A tibble: 2 x 4
  mytext1 mytext2 value1 value2
    <chr>   <chr>  <dbl>  <dbl>
1   HELLO   HELLO      1      1
2   WORLD   AGAIN      2      2

I would like to export this dataframe to a latex table, but with some little (but important) tweaks.

In particular, I would like, in the latex output, to add a supercolumn that separates the text variables and another that separates the numeric variables. That is, something in the spirit of mat and com in this image:

enter image description here

I tried the R packages xtable and tables but I was unable to achieve something close (likely because they create summary statistics tables). Am I missing something here?

Thanks!

1

There are 1 answers

6
Marius On BEST ANSWER

You can do this using kable from the knitr package plus the kableExtra package:

```{r table, results='asis'}
library(knitr)
library(kableExtra)
library(magrittr)

dataframe <- data.frame(mytext1 = c('HELLO',
                                   'WORLD'),
                        mytext2 = c('HELLO',
                                   'AGAIN'),
                        value1 = c(1,2), 
                        value2 = c(1,2))

dataframe %>%
    kable(format = 'latex', booktabs = TRUE) %>%
    add_header_above(header = c("Text" = 2, "Values" = 2))
``` 

Here I've shown the code included in an RMarkdown chunk, where the table is automatically included when knitting to PDF, but the code should also work on its own outside of RMarkdown.

Running the code by itself you get the Latex code for the table as output:

\begin{tabular}{llrr}
\toprule
\multicolumn{2}{c}{Text} & \multicolumn{2}{c}{Values} \\
\cmidrule(l{2pt}r{2pt}){1-2} \cmidrule(l{2pt}r{2pt}){3-4}
mytext1 & mytext2 & value1 & value2\\
\midrule
HELLO & HELLO & 1 & 1\\
WORLD & AGAIN & 2 & 2\\
\bottomrule
\end{tabular}