3

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?

Hank Lin
  • 5,959
  • 2
  • 10
  • 17

2 Answers2

4

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

akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks akrun! Do you know what the issue with my original attempt is? I thought it has to do with the print() treating the argument as output instead of raw html. However, if I try to do `for (i in 1:2) tables[[i]]` I get nothing at all in the knitted output! – Hank Lin Nov 22 '21 at 21:08
  • 2
    @HankLin according to `?knit_print` -`the chunk option render is a function that defaults to knit_print().` – akrun Nov 22 '21 at 21:15
  • surprisingly, the `cat()` after `knit_print()` is essential in some cases, e.g. when calling the .Rmd from `render()`. Any ideas why the `cat()` call is necessary? – Agile Bean Dec 04 '22 at 05:29
2

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

TarJae
  • 72,363
  • 6
  • 19
  • 66