Search code examples
htmlrr-markdownknitrgtsummary

Rmarkdown HTML rendering issue


I am trying to print a list of HTML tables, but for some reason when I knit the document, I get the raw HTML code for output instead of the rendered table. Example:

---
title: "html-render-issue"
output: html_document
---
library(tidyverse)
library(gtsummary)

# this table renders correctly:
tbl_summary(iris)

# but this table does not!!
tables <- list(tbl_summary(iris), tbl_summary(cars))
print(tables)

I don't understand why this is happening, I tried indexing into the list with a for loop

for (i in 1:2) {
  print(tables[[i]])
}

but this doesn't seem to work either! Short of doing tables[[1]]; tables[[2]] etc. (which does work), is there a way to iterate over the list and get the output I want?


Solution

  • Try with adding %>% as_gt() within the list!

    ---
    title: "html-render-issue"
    output: html_document
    ---
    
    ```{r loop_print, results = 'asis'}
    library(tidyverse)
    library(gtsummary)
    
    tables <- list(tbl_summary(iris), tbl_summary(cars) %>%  as_gt())
    walk(tables, print)               # walk from purrr package to avoid [[1]] [[2]]
    ```
    

    enter image description here