Using map() with gt() in a RMD file returns HTML code instead of the rendered tables

Suppose I have the following RMD file:

---
title: "Untitled"
author: "me"
date: "2023-01-23"
output: html_document
---
 
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```

```{r}
library(dplyr)
library(gt)

mydf <- tibble::tribble(
  ~tab1_d1, 	~tab1_d2, 	~tab1_d3, 	~tab1_cd_1, 	~tab1_cd_2, 	    ~tab1_cd_3, 	~tab1_cvd2,
  1, 	1, 	0, 	0, 	1, 	0, 	1,
  0, 	1, 	0, 	0, 	1, 	0, 	1,
  1, 	0, 	0, 	1, 	0, 	0, 	0
)

print_table <- function(x) {
       mydf |> 
         mutate(cat = if_else(!! sym(x) == 1, "Available", "Not available") |> 
                  forcats::fct_expand("Available", "Not available")) |> 
         count(cat, .drop = FALSE) |> 
         tidyr::pivot_wider(names_from = cat, values_from = n) |> 
         mutate(Total = Available + `Not available`) |> 
         gt() |> 
         tab_header(glue::glue("{x} - Is high quality data available?"))
}

purrr::map(names(mydf), print_table)
```

If I were to run the code outside of markdown, it does what it is supposed to do - list out a bunch of gt tables. But when I knit this RMD file, it spits out HTML code without rendering it. How would I get it to properly render?

I believe that a good solution is to send your results to the function htmltools::tagList()

htmltools::tagList(purrr::map(names(mydf), print_table))
1 Like