Search code examples
rr-markdownbeamer

[rmarkdown]How to deal with table in beamer_presentation


When I embed a table generated by using knitr::kable, I want to adjust the width of the table in beamer_presentation's slide.

Like this picture, some columns don't show in slide when executing the following codes. enter image description here

Could you tell me how to solve this problem without changing column's names?

---
title: "test"
author: "test"
date: "`r Sys.time()`"
output:
   beamer_presentation:
     latex_engine: xelatex 

fontsize: 6pt 
---

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

```


## Table
```{r test, results = "asis",include=TRUE}

test_tbl = tibble(
  example_name1 = c("a", "b"),
  example_name2 = c("aa", "bb"),
  example_name3 = c("aaa", "bbb"),
  example_name4 = c("aaaa", "bbbb"),
  example_name5 = c("aaaaa", "bbbbb")
)


knitr::kable(test_tbl, format = "markdown")
```

Solution

  • The table is too large to fit on one slide. By adjusting the font size with kableExtra the size of the table can be changed. To do this, set the argument format = "latex" in kable() and then pipe kable_styling().

    knitr::kable(test_tbl, format = "latex") %>%
      kableExtra::kable_styling(font_size = 7) 
    

    It is useful to include LaTeX packages like booktabs to format tables nicely with kable or kableExtra. This is not as flexible as working with LaTeX directly but often leads to quite good results.

    First of all, include booktabs in the YAML header.

    ---
    title: "test"
    author: "test"
    date: "`r Sys.time()`"
    header-includes:
    - \usepackage{booktabs}
    output: beamer_presentation
    ---
    

    Then set booktabs = TRUE in kable().

    knitr::kable(test_tbl, format = "latex", booktabs = T) %>%
      kableExtra::kable_styling(font_size = 7) 
    

    enter image description here