rlatexknitrkablernw

How to handle the overlay of kable output with page number?


I use kbl() function, in a rnw file that I compile in a pdf with knitr, to make a table starting from a dataframe. I use kableExtra option scale_down to adapt the table size to page size. It works fine but the table overlay with the page number of my pdf output. I'd like to know what's the best way to handle this type of problem. Thanks in advance for the help.


Solution

  • You could add some Latex code that puts the tabular environment into a box and resizes the content. Below is an example using \resizebox

    Here's tab, a LaTex table with Gaussian random numbers generated by kable:

    ```{r, message = F, warning=F}
    library(knitr)
    library(tidyverse)
    library(kableExtra)
    
    ncol <- 10
    nrow <- 30
    df <- map_dfc(1:ncol, ~ data.frame(round(rnorm(nrow), 2))) %>% 
      set_names(letters[1:ncol])
    
    tab <- kbl(df, format = "latex")
    ```
    

    And here's how to resize it by text height/width using resizebox (see this post on tex.stackexchange for details on how the scaling works)

    ```{r, results='asis'}
    cat(
    "\\begin{table}
    \\centering
    \\resizebox*{\\textwidth}{\\dimexpr\\textheight-2\\baselineskip\\relax}{%",
    tab,
    "\n}
    \\end{table}"
    )
    ```
    

    Result for the 30x10 table

    enter image description here

    Let's double rows and columns (ncol <- 20; nrow <- 60)

    Result for 60x20 table.

    enter image description here