有没有一种直接的方法可以在R Markdown文档的循环中打印DiagrammeR
对象?我有一个文档,其中为多个模型分别生成了回归表、绘图和图表,并打印在一起。使用for循环很容易做到这一点,但DiagrammeR
对象不会在循环中打印(即使使用像print(graph)
.这样的显式调用
其他地方对此进行了记录(参见:https://github.com/rich-iannone/DiagrammeR/issues/39(,但2015年提出的解决方案现在似乎不起作用(仅限于html输出(。
请参阅下面的Rmd示例代码。
---
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)
}
以下是修复方法:
# 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