Home > Enterprise >  how to convert a node list to an edge list in igraph?
how to convert a node list to an edge list in igraph?

Time:10-29

I have a empty graph and need to plot the graph based on the convex hull with inner verticies.

My attemp is:

library(igraph)
set.seed(45)
n = 10

g <- graph.empty(n)
xy      <- cbind(runif(n), runif(n))
    
vp <- convex_hull(xy)$resverts   1
#[1]  8 10  7  2  1

## convert node_list to edge_list

plot(g, layout=xy)

Expected result in right figure.

enter image description here

Question. How to convert a node list to an edge list in igraph??

CodePudding user response:

convex_hull does not output a node list in the same sense that an igraph object has a node list. In this case, vp is the sequence of indices so in order to create an edge list, you just need to have the from vertex be going to the next vertex in the sequence. This can be accomplished with dplyr::lead using the first vertex as the default to create a circuit.

data.frame(
  from = vp,
  to = dplyr::lead(vp, 1, default = vp[1])
)
#>   from to
#> 1    8 10
#> 2   10  7
#> 3    7  2
#> 4    2  1
#> 5    1  8

CodePudding user response:

You can use add_edges along with embed

g2 <- g %>%
  add_edges(c(t(embed(vp, 2)), vp[1], vp[length(vp)])) %>%
  as.undirected()

and plot(g2, layout = xy) in turn gives

enter image description here

  • Related