rvisnetwork

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


My visNetwork is not displayed at all when the displaying is attempted in a for loop. In a regular R script, I use the print function and it works just fine, but it does not work in an R Markdown document.

Here is a (hopefully) reproducible example:

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

I'm using Rstudio version Version 1.1.383 and here is the result of a 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

Solution

  • I just found a little workaround, consisting the following steps:

    Here an example:

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