rigraph

Connect a single point to all points in a graph


I have this graph in R:

library(igraph)
set.seed(123)

n_nodes <- 20
g <- erdos.renyi.game(n_nodes, p=0.2)

V(g)$name <- 1:n_nodes

layout <- layout_with_fr(g)
plot(g,
     layout = layout,
     vertex.size = 15,
     vertex.label = V(g)$name,
     vertex.color = "lightblue",
     vertex.label.color = "black",
     vertex.label.cex = 0.8,
     edge.arrow.size = 0.5,
     main = "Original Random Network")

enter image description here

I am trying to connect "node 1" with all other nodes on the graph.

Currently, I am doing this manually:

g_modified <- g  

new_edges <- c()
for(i in 2:n_nodes) {
    if(!are.connected(g_modified, 1, i)) {
        new_edges <- c(new_edges, 1, i)
    }
}

g_modified <- add.edges(g_modified, new_edges)
# I colored them to make it clearer
incident_edges <- incident(g_modified, 1, mode="all")
edge_colors <- rep("gray", ecount(g_modified))
edge_colors[incident_edges] <- "red"

The final result looks like this:

enter image description here

I am just wondering - is there some function in igraph that can automatically do this without having to use this loop approach?


Solution

  • You could use add_edges with the appropriate elements, here, created using a matrix.

    g %>%
      add_edges(c(t(matrix(c(rep(1, 19), 2:20), nr=19)))) %>%
      plot()
    

    enter image description here