edgebundle 调用返回一个htmlwidget 并且正如您所指出的,在不在循环中时也可以正常工作。针对您的情况的解决方案是使用 for 循环在临时文件中生成几个特定的 R 代码块,然后将该临时文件作为主 .Rmd 文件中的子文件进行评估。
例如,在 .Rmd 文件中,这两个块将加载所需的包并定义一个函数 foo,该函数创建并显示一个随机的边束。
```{r}
set.seed(42)
library(edgebundleR)
library(igraph)
```
## test the function
```{r}
foo <- function() {
adjm <- matrix(sample(0:1, 100, replace = TRUE, prob = c(0.6, 0.4)), nc = 10)
g <- graph.adjacency(adjm)
edgebundle(g)
}
```
在一个块中调用foo 两次将在输出.html 文档中按预期工作。
```{r}
foo()
foo()
```
要在for 循环中生成多个边缘预算,请尝试此操作。编写一个 for 循环以使用所需的 R 块填充 temp.Rmd 文件。您需要根据您的应用程序的需要对其进行修改。
## test the function in a for loop
```{r}
tmpfile <- tempfile(fileext = ".Rmd")
for(i in 1:3) {
cat("### This is edgebundle", i, "of 3.\n```{r}\nfoo()\n```\n",
file = tmpfile, append = TRUE)
}
```
tmpfile 的内容如下所示:
### This is edgebundle 1 of 3.
```{r}
foo()
```
### This is edgebundle 2 of 3.
```{r}
foo()
```
### This is edgebundle 3 of 3.
```{r}
foo()
```
要在主输出文件中显示小部件,请使用如下块:
```{r child = tmpfile}
```
完整的.Rmd 文件和结果:
example.Rmd:
# edgebundleR and knitr
Answer to https://stackoverflow.com/questions/47926520/edgebundle-doesnt-render-plot-when-in-loop-in-markdown
```{r}
set.seed(42)
library(edgebundleR)
library(igraph)
```
## test the function
```{r}
foo <- function() {
adjm <- matrix(sample(0:1, 100, replace = TRUE, prob = c(0.6, 0.4)), nc = 10)
g <- graph.adjacency(adjm)
edgebundle(g)
}
foo()
foo()
```
## test the function in a for loop
```{r}
tmpfile <- tempfile(fileext = ".Rmd")
for(i in 1:3) {
cat("### This is edgebundle", i, "of 3.\n```{r}\nfoo()\n```\n",
file = tmpfile, append = TRUE)
}
```
```{r child = tmpfile}
```
```{r}
print(sessionInfo(), local = FALSE)
```