Printing gt table inside a loop with rmarkdown::render not working
Asked Answered
B

1

8

I am programming a report generator that export html. I use two files, the first is a loop that will determine the number of reports and within my .Rmd template I have another loop to print several tables.

The .Rmd below, works fine

    ---
title: "Report"
author: "Me"
date: "`r format(Sys.time(), '%d de %B de %Y')`"
output:
  html_document
---

# First Section


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

i=1

df <- cbind(m=c(rep(1,16),rep(2,16)),mtcars)

gears <- unique(df$gear)

for(g in gears)
{
  cat("## gear", g, "\n")
  
  print(
  df %>% filter(gear==g & m==i) %>%
    gt()
  )
}

The output enter image description here

but if call it from the external file with render the tables do not show

library(tidyverse)
library(gt)

df <- cbind(m=c(rep(1,16),rep(2,16)),mtcars)

for (i in 1:2) 
{

  rmarkdown::render(
    'report_template_2.Rmd', output_file = paste0("report", 
                                                    "_",i, 
                                                  '.html'), encoding="UTF-8")
}

enter image description here

Benghazi answered 26/3, 2021 at 7:51 Comment(0)
D
6

The usual htmltools::tagList trick seems to work.
Didn't dig into render internals to try to understand why it behaves differently than manual knit.

---
title: "Report"
author: "Me"
date: "`r format(Sys.time(), '%d de %B de %Y')`"
output:
  html_document
---

# First Section

```{r,eval=F,echo=F}
gt(mtcars)
```


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

i=1

df <- cbind(m=c(rep(1,16),rep(2,16)),mtcars)

gears <- unique(df$gear)

l <- list()
i<-1
for(g in gears)
{
  cat("## gear", g, "\n")
  
  print(htmltools::tagList(df %>% filter(gear==g & m==i) %>% gt()))

}

enter image description here

Dotty answered 6/5, 2021 at 7:30 Comment(3)
Is there a possibility to modify this, to show two different gt tables from within a loop?Inwrap
@R_lump, if I understand your question correctly, you could use print(htmltools::tagList(...)) %>% ... %>% gt() twice within the loop, this should show the content of 2 different tables.Dotty
In my case I just added print. I did not need to use htmltools::tagList to fix my looping gt issue. I returned gt from a function which executed fine when I did not use a for loop.Pederasty

© 2022 - 2024 — McMap. All rights reserved.