简体   繁体   中英

Scale kable table to fit page width

How do you format a table in pdf using kable function? Because my output table width exceeds the width of the pdf. Here is an example:

---
output: pdf_document
---

```{r}
df <- cbind(mtcars[1:5,], mtcars[1:5,])
knitr::kable(df)
```

在此处输入图片说明

One option is to use kable_styling from the kableExtra package. The option latex_options="scale_down" will fit the table within the paper margins. Seethe vignette for detailed examples on all of the formatting options.

---
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(knitr)
library(kableExtra)
```

```{r}
kable(cbind(mtcars[1:5,], mtcars[1:5,]))
```

```{r}
kable(cbind(mtcars[1:5,], mtcars[1:5,]), format="latex", booktabs=TRUE) %>% 
  kable_styling(latex_options="scale_down")
```

在此处输入图片说明

Note if you are using longtable, this answer says,

since longtable doesn't support resizebox, you cannot use the "scale_down" option in latex_options.

However, they suggested using font_size, eg,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM