Remove self-loop in visNetwork

81 Views Asked by At

I want to remove the self-loop in visNetwork, how can I do it?

library(visNetwork)
nodes <- data.frame(id = 1:3)
edges <- data.frame(from = c(1,2), to = c(1,3))
visNetwork(nodes, edges, width = "100%")

enter image description here

I tried to add the following code, but it still did not work.

edges$value = 1
edges$value = ifelse(edges$from == edges$to, 0, edges$value)
2

There are 2 best solutions below

0
zx8754 On BEST ANSWER

We can remove edges where from is same as to before plotting:

library(visNetwork)

visNetwork(nodes = nodes, edges = edges[ edges$from != edges$to, ])

enter image description here

0
ThomasIsCoding On

You can try simplify from igraph before calling visNetwork

library(visNetwork)
library(igraph)

edges %>%
  graph_from_data_frame() %>%
  simplify() %>%
  toVisNetworkData() %>%
  {
    visNetwork(.$nodes, .$edges, width = "100%")
  }

which produces a graph like

enter image description here