Search code examples
rbookdown

In R bookdown, how to code a very large table (120 row, 8 columns) for pdf and html outputs?


In an R bookdown code, I want to output a very large table in a neat way. I want to present a very large table in my pdf output (bookdown::pdf_book), html output (bookdown::git_book) and also if possible in ebook (bookdown::epub_book) outputs. My table has about 120 rows and 8 columns, where each cell has varying lengths and formats. Two of the cells some times has about 25 chara ters long (if possible I want them to go to the next line automatically if it exceeds the maximum length of a cell). Tha table might be presented in parts to pdf pages automatically is the ideal solution I am looking for. Thanks

kable function was OK with shorter tables so far but not sure on the large ones.


Solution

  • For gitbook, you don't have to worry about the long table since there's no page height limit.

    For PDF you can go with kableExtra as the comment suggested above. Here is an example to format the long table. It also wraps up the 13th column with long text.

    ---
    title: "Untitled"
    date: "6/25/2019"
    output: bookdown::pdf_book
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    ```
    
    
    Here is an example to show the long table by using kableextra.
    
    
    ```{r}
    library(kableExtra)
    
    df = rbind(mtcars, mtcars, mtcars)
    
    df$alongcol = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin vehicula tempor ex. Morbi malesuada sagi"
    
    kable(df,
          booktab = TRUE,
          longtable = TRUE,
          caption = "example") %>%
      kable_styling(latex_options = c("repeat_header")) %>%
      column_spec(13, width = "10em")
    
    
    
    ```