edgebundle 在降价循环中不渲染绘图

edgebundle doesn't render plot when in loop in markdown

我正在尝试创建一个自动报告,其中我使用 edgebundleR 创建了一系列和弦图。

我有一个函数可以做很多事情并且或多或少有这种形式:

plot_chords <- function(x,t,pos) {
  ...
  stuff I do with the data
  ...
  g <- graph.adjacency(mydata, mode="upper", weighted=TRUE, diag=FALSE)
  return(edgebundle(g))
}

如果我不在循环中使用这个函数,它可以正常工作。如果它处于这样的循环中则不会:

```{r echo = FALSE,message=FALSE, warning = FALSE,results = "asis"}
for (c in unique(df$Group)) {

  cat("\n\n## ",c," - Negative Correlations (min r=",t_neg," - only significative)\n\n")
  plot_chords(subset(df, Group == c),0.5,0)

}
```

我发现一般来说,这在循环内不起作用,除非我使用 print:

for (c in unique(df$Group)) {
  temp=df[df$Group == c,]
  print(plot_chords(temp,0.5,0))
}

但是打印在 markdown 中不起作用。

如何渲染情节?

谢谢。

edgebundle 调用 returns 一个 htmlwidget 并且如您所指出的那样在不在循环中时运行良好。针对您的情况的解决方案是使用 for 循环在临时文件中生成几个特定的​​ R 代码块,然后将该临时文件评估为主 .Rmd 文件中的子文件。

例如,在 .Rmd 文件中,这两个块将加载所需的包并定义一个函数 foo,它创建并显示一个随机的 edgebundle。

```{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 循环中生成多个 edgebudles,试试这个。编写一个 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 

```{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)
```