Search code examples
rr-markdownreactable

reactable in R markdown `asis` chunk with loop not displayed


I want to create dynamic sections in my R markdown document. For this, I use R chunks with the asis output type. The chunks contain tables created by the reactable package.

I cannot get the tables to print when I create them in a for-loop. I know that one usually must wrap plots or the like within print() in loops, but that had no effect in my case.

How can I get the tables to print?

---
title: "Test"
author: "Test"
date: "29 11 2021"
output: html_document
---

```{r include=FALSE}
library(reactable)

```

```{r results='asis', echo=FALSE}

cat("\n\n## My header 1 \n\n")

reactable(data.frame(test = rnorm(3)))  ## This works

```



```{r results='asis', echo=FALSE}



for (i in 1:3) {
  
  cat("\n\n## My header ", i+1, "\n\n")
  
  print(reactable(data.frame(test = rnorm(3))))  ## shows nothing
  
}

```

Solution

  • I just found out, that reactable uses htmlwidgets under the hood. So one can wrap the result in shiny::tagList() to display it in a loop.

    ---
    title: "Test"
    author: "Test"
    date: "29 11 2021"
    output: html_document
    ---
    
    ```{r include=FALSE}
    library(reactable)
    
    ```
    
    ```{r results='asis', echo=FALSE}
    
    cat("\n\n## My header 1 \n\n")
    
    reactable(data.frame(test = rnorm(3)))  ## This works
    
    ```
    
    
    
    ```{r results='asis', echo=FALSE}
    
    
    for (i in 1:3) {
      
      cat("\n\n## My header ", i+1, "\n\n")
      
      print(shiny::tagList(reactable(data.frame(test = rnorm(3)))))  ## now it works
      
    }
    
    ```