Home > Enterprise >  Rmarkdown HTML rendering issue
Rmarkdown HTML rendering issue

Time:11-23

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?

CodePudding user response:

Consider using results = "asis" in the r chunk and then instead of print use knitr::knit_print

```{r, results = "asis", echo = FALSE}
 library(gtsummary)

 # this table renders correctly:
 tbl_summary(iris)

 # but this table does not!!
 tables <- list(tbl_summary(iris), tbl_summary(cars))
 for (i in 1:2) {
   cat(knitr::knit_print(tables[[i]]))
 }
```

-output

enter image description here

CodePudding user response:

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

  • Related