简体   繁体   中英

Add a node and delete an specified edge in R igraph

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.

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)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM