Search code examples
rdiagrammer

Print DiagrammeR object inside for-loop


Is there a straightforward way to print DiagrammeR objects from within a loop in an R Markdown document? I have a document in which a regression table, a plot and a diagram are each generated for multiple models and printed together. It's easy to do this with a for-loop but the DiagrammeR object won't print inside a loop (even with an explicit call like print(graph).

This has been documented elsewhere (see: https://github.com/rich-iannone/DiagrammeR/issues/39 ) but the suggested solution from 2015 does not appear to work now (and is limited to html output).

See example code for an Rmd below.

---
title: "DiagrammeR loop test"
author: ""
date: "11/20/2020"
output: pdf_document
---


# Some header
Printing a single flowchart works fine in knitr using the DiagrammeR package. 

```{r figure_1, out.width = "15%", echo = FALSE, fig.align = 'center', fig.cap = "Flowchart 1: This prints fine."}

DiagrammeR::grViz(" 
      digraph test {

        node [shape = circle] 
          A; B

        A -> B

      }
        ")

```

Flowchart 2 which is inside a loop, however, does not print 


```{r figure_2, out.width = "15%", echo = FALSE, fig.align = 'center', fig.cap = "Flowchart 2: These two diagrams do not print even with an explicit print command."}

for (i in 1:2){
  
graph <- DiagrammeR::grViz(" 
      digraph test {

        node [shape = circle] 
          A; B

        A -> B

      }
        ")

print(graph)  
}

Solution

  • Here is how to fix it:

    # Create an empty list to save the htmlwidgets
    plot_list <- htmltools::tagList()
    
    for (i in 1:2){
      
    graph <- DiagrammeR::grViz(" 
          digraph test {
    
            node [shape = circle] 
              A; B
    
            A -> B
    
          }
            ")
    
    # Store the htmlwidget inside this list
    plot_list[[i]] <- graph 
    }
    
    #Print this list
    plot_list