gpt4 book ai didi

R Markdown : visNetWork not displayed in html output when using for loops (or functions)

转载 作者:行者123 更新时间:2023-12-04 01:39:58 26 4
gpt4 key购买 nike

当在 for 循环中尝试显示时,根本不显示我的 visNetwork。在常规的 R 脚本中,我使用 print 函数,它工作得很好,但它在 R Markdown 文档中不起作用。

这是一个(希望是)可重现的例子:

---
title: "I want my beautiful networks back!"
---

# First example that works

```{r}
require(visNetwork, quietly = TRUE)
# minimal example
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
vn <- visNetwork(nodes, edges, width = "100%")
vn # Or print(vn)
```

# When does it not work?

## In a for loop

```{r}
for (i in 1) vn
```

## In a for loop + using print

This will display the network in the Viewer.

```{r}
for (i in 1) print(vn)
```

## And also in functions

Same remark...

```{r}
foo <- function(x) print(x)
foo(vn)
```

我使用的是 Rstudio 版本 1.1.383 和这是 sessionInfo()

的结果
R version 3.4.2 (2017-09-28)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6

other attached packages:
[1] visNetwork_2.0.2

最佳答案

我刚刚找到了一个解决方法,包括以下步骤:

  • 将绘图另存为 HTML
  • 在 RMD 文件中包含 HTML 代码

这里是一个例子:

```{r}
for (i in 1:3){
visSave(vn, file = paste0("test",i,".html"))
}
```

```{r, results='asis'}
for (i in 1:3){
cat(htmltools::includeHTML(paste0("test",i,".html")))
}
```

关于R Markdown : visNetWork not displayed in html output when using for loops (or functions),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47577894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com