Is there a way to export multiple gt tables to a single HTML output

Viewed 37

I have a list of many (can be dozens of) tables created with the gt package in R. I would like to export them all as a single HTML file with a little space between each table. Currently, I have been exporting each table individually, reading them into an RMarkdown with the xfun package, and knitting to a single HTML file. I'm curious if there is a method to cut out the intermediate step of saving each table individually and reading into the Rmd.

Example:

library(gt)
library(tidyverse)

tbl_list <- list(mtcar_tbl = mtcars %>% gt(),
     iris_tbl  = iris %>% gt(),
     cars_tbl  = cars %>% gt())

purrr::map(seq_along(tbl_list), function(rownum){
  htmltools::save_html(html = tbl_list[[rownum]],
                       file = paste0("test",rownum,".html"))
})

RMarkdown to combine and export tables:

---
title: ""
output: html_document
---

```{r, echo=FALSE,message=FALSE,warning=FALSE}
library(xfun)
```

```{r echo=FALSE}
htmltools::includeHTML("test1.html")
```

<br><br>

```{r echo=FALSE}
htmltools::includeHTML("test2.html")
```

<br><br>

```{r echo=FALSE}
htmltools::includeHTML("test3.html")
```
1 Answers

One option would be to use purrr::walk with chunk option results="asis" to directly print your tables without the intermediate step. To add the line breaks after each table use cat("<br><br>"):

Note: For the reprex I just print the head of each table.

---
title: "Untitled"
output: html_document
date: "2022-09-19"
---

```{r echo=FALSE, results='asis', warning=FALSE, message=FALSE}
library(gt)
library(tidyverse)

tbl_list <- list(mtcar_tbl = mtcars,
     iris_tbl  = iris,
     cars_tbl  = cars)
tbl_list <- purrr::map(tbl_list, ~ head(.x) %>% gt() )

purrr::walk(tbl_list, function(x) { print(x); cat("<br><br>") })
```

enter image description here

Related