Search code examples
rr-markdownioslides

How to fit large frequency table into R markdown ioslides?


I'm trying to fit large table of frequencies into my slide. There are many values, and even the rare ones would be nice to show.

I played with different options but none gives me a satisfactory solution. Here is Rmd so far:

---
title: "Untitled"
author: "author"
date: "date"
output: ioslides_presentation
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
df <- as.data.frame(table(rownames((USArrests))))
```

## table 1

```{r t1, echo = TRUE}
table(rownames((USArrests)))
```

## table 2

```{r t2}
library(knitr)
library(kableExtra)
kable(df, "html") %>%
  kable_styling(bootstrap_options = "striped", font_size = 10)
```

Table 1 doesn't fit:

enter image description here

Table 2 could be squeezed but with tiny font, and lots of wasted space on the sides.

I also looked into pander, xtable and stargazer but failed to find solution from them either.

Any other alternatives?


Solution

  • You could spread your table across multiple columns to fit the space. In my example below, I split the frame up into 3 pairs of columns with uneven length.

    ---
    output: ioslides_presentation
    ---
    
    ```{r setup, include=FALSE}
    library(dplyr)
    library(magrittr)
    library(knitr)
    library(kableExtra)
    ```
    
    ## table 1
    
    ```{r, echo=TRUE, eval=FALSE}
    USArrests %>% rownames %>% table
    ```
    
    ```{r, echo=FALSE}
    df <- USArrests %>%
      rownames %>%
      table %>%
      as_tibble
    
    df %$%
      tibble(
        name1 = `.`[1:17],
        n1 = n[1:17],
        name2 = `.`[18:34],
        n2 = n[18:34],
        name3 = c(`.`[35:50], ""),
        n3 = c(n[35:50], "")
      ) %>%
      kable("html", align = c("l", "c"), col.names = rep(c("Name", "Frequency"), 3)) %>%
      kable_styling(bootstrap_options = c("striped", "condensed"), font_size = 18)
    ```
    

    enter image description here

    N.B. I accept the transform step into multiple columns could have been done more elegantly and providing and more programmatic solution, however, I'll leave that to others to refine.