how to export a dataframe to latex with some minimal formatting?
Asked Answered
A

1

1

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!

Amor answered 29/8, 2017 at 1:5 Comment(0)
C
6

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}
Corpus answered 29/8, 2017 at 1:16 Comment(6)
Thanks Marius! but I would like to get a latex table so that I can include in my main tex fileEndowment
Yes, as I said this works outside of RMarkdown as well, it outputs the latex code for the table.Corpus
haha wonderful!!! do you know if there is an option to remove the begin{tabular} and end{tabular} line?Endowment
Doesn't look like it, there a few different options to use plain table, booktabs or longtable but I don't think there's an option for suppressing those.Corpus
Marius, please have a look here. I think its worth another questionEndowment
#45930171Endowment

© 2022 - 2024 — McMap. All rights reserved.