2

I'm creating a flow chart with the R package diagrammer. To get desired formatting (bold, bullet, left-justify) I can write node label in html. However, I also want to populate some of the text by calling variables in R, and I can't figure out how to do both (html formatting + call R variables) at the same time.

In this code snippet, the html formatting works but instead of printing the string assigned to the variable 'text_var', it prints the string 'text_var'.

library(DiagrammeR)

text_var = 'Some text'

grViz("digraph flowchart {
      # Node definitions
      node [fontname = Helvetica, shape = box]        
      tab1 [label = <<b> Node 1 </b> <br ALIGN = 'LEFT' /> &#8226; text_var  <br ALIGN = 'LEFT' /> 
                    >]
      tab2 [label = 'Node 2']

      # Edge definitions
      tab1 -> tab2 


      }")

enter image description here

In this code snippet, I am print the string assigned to the variable 'text_var', but there's no html.

library(DiagrammeR)

text_var = 'Some text'

grViz("digraph flowchart {
      # Node definitions
      node [fontname = Helvetica, shape = box]        
      tab1 [label = '@@1']
      tab2 [label = 'Node 2']

      # Edge definitions
      tab1 -> tab2 
}

      [1]: paste0('Node 1 \\n ', text_var)


      ")

enter image description here

Desired result is the text from the second example with the formatting from the first. Thank you!

Alton
  • 137
  • 6

2 Answers2

4

Although the solution by Allan Cameron works, it is also possible to use Graphviz Substitution.

I found the implementation rather buggy however, although @@1 should work in the below example, I found that it took over 3 minutes of full CPU usage before I shut it off. @@1-1 seems to work.

text_var = 'Some text'

grViz("
  digraph flowchart {
    # Node definitions
    node [fontname = Helvetica, shape = box]        
    tab1 [label = <
                   <b>Node 1</b>
                   <br ALIGN = 'LEFT' /> 
                     &#8226; @@1-1
                   <br ALIGN = 'LEFT' /> 
                  >]
    tab2 [label = 'Node 2']

    # Edge definitions
    tab1 -> tab2 
  }
  [1]: text_var"
)

enter image description here

nograpes
  • 18,623
  • 1
  • 44
  • 67
  • While the other solution works well for the toy example, this seems better suited for referencing several R variables. Thank you! – Alton Jan 13 '20 at 20:21
3

R doesn't know that you want the string "text_var" inside the string you are passing to grViz to be replaced by the actual variable text_var containing your string. Try this instead:

grViz(gsub("text_var", text_var, "digraph flowchart {
      # Node definitions
      node [fontname = Helvetica, shape = box]        
      tab1 [label = <<b> Node 1 </b> <br ALIGN = 'LEFT' /> &#8226; text_var  <br ALIGN = 'LEFT' /> 
                    >]
      tab2 [label = 'Node 2']

      # Edge definitions
      tab1 -> tab2 


      }"))
    ```
Allan Cameron
  • 147,086
  • 7
  • 49
  • 87