在 for 循环中打印 DiagrammeR 对象
Print DiagrammeR object inside for-loop
在 R Markdown 文档的循环中是否有直接打印 DiagrammeR
对象的方法?我有一个文档,其中为多个模型分别生成了一个回归 table、一个绘图和一个图表,并一起打印。使用 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
在 R Markdown 文档的循环中是否有直接打印 DiagrammeR
对象的方法?我有一个文档,其中为多个模型分别生成了一个回归 table、一个绘图和一个图表,并一起打印。使用 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