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

320 views Asked by At

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.

2

There are 2 answers

2
Martin C. Arnold On BEST ANSWER

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

2
Quinten On

I have three suggestions. The first one is maybe set your table to the next page using \newpage in your Rmarkdown code which is latex code. The second option is maybe set latex_options="HOLD_position" in your Kable_styling function. This will set the table at a certain place which maybe could help your problem. The third option is using 'longtable = TRUE` which means that the table continues on the next page. Here is the code for option one and two with:

```{r}
library(knitr)
library(tidyverse)
library(kableExtra)

df <- data.frame(x = 1:10, y = 11:20)

kable(df) %>%
  kable_styling(latex_options = "HOLD_position")

```

\newpage

```{r}

kable(df) %>%
  kable_styling(latex_options = "HOLD_position")

```

Which looks like this:

enter image description here

Here is the code for option three:

```{r}
library(tidyverse)
library(knitr)
library(kableExtra)
df <- data.frame(x = 1:50, y = 11:60)

kable(df, "latex", longtable = T, booktabs = T) %>%
  kable_styling(latex_options = c("repeat_header"), font_size = 7) 
```

Looks like this:

enter image description here