Reputation: 3557
I am learning igraph in R and have a question on how to add a node to the graph and delete an edge by specifying its two nodes. Here is my code to create a graph with 4 nodes and some edges.
g <- as.data.frame(cbind(matrix(c(1, 2, 1, 3, 1, 4, 3, 4, 2, 4), byrow = TRUE, ncol = 2), c(5.6, 2.7, 3.5, 1.8, 2.1)))
names(g) <- c("start", "end", "length")
g <- graph.data.frame(g, directed = FALSE)
plot(g)
Here length
denotes the attribute the edge (the length of the edge). I want to add a node 5 to the graph. This node will be between 1 and 2. Now the length of the edge 1--2 is 5.6. Node 5 will have a distance of 2.6 from node 1 and a distance of 3.0 from node 2. I want to add these two edges (1--5 and 2--5). I also need to remove the 1--2 edge by telling R to delete the edge between node 1 and node 2.
What's a simple way of doing this? Thank you.
Upvotes: 2
Views: 2656
Reputation: 78832
Something like:
library(igraph)
g <- as.data.frame(cbind(matrix(c(1, 2, 1, 3, 1, 4, 3, 4, 2, 4),
byrow = TRUE, ncol = 2),
c(5.6, 2.7, 3.5, 1.8, 2.1)))
names(g) <- c("start", "end", "length")
g <- graph.data.frame(g, directed = FALSE)
# add node 5
g <- g + vertices(5)
# delete edge 1-2
g["1", "2"] <- NULL
# add new edges with length attribute
g <- g + edge("1", "5", attr=list(length=2.6))
g <- g + edge("2", "5", attr=list(length=1.3))
plot(g)
Upvotes: 5