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

别来无恙 提交于 2019-12-24 19:23:31

问题


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:

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:


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}


来源:https://stackoverflow.com/questions/45929263/how-to-export-a-dataframe-to-latex-with-some-minimal-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!