R语言基于igraph创建Graph类的正确性验证及方法实现咨询
Hey there! As someone who’s spent plenty of time tinkering with igraph in R, let’s break down your questions clearly:
Absolutely! The line g1 <- graph_from_adjacency_matrix(adjMatrix, mode="directed", weighted =TRUE) is a totally valid way to create a directed, weighted graph from an adjacency matrix. A quick note to confirm:
mode="directed"ensures edges go from row nodes to column nodes (soadjMatrix[i,j]represents an edge from node i to node j)weighted=TRUEtells igraph to use the non-zero values in your adjacency matrix as edge weights. If your matrix uses 0 to represent "no edge", this works perfectly—igraph will only create edges where the matrix has a non-zero value.
Let’s cover the specific operations you asked about:
Adding Nodes
Use the add_vertices() function to add nodes, and you can even attach custom attributes at the same time:
- Add a single node:
g1 <- add_vertices(g1, 1) - Add multiple nodes with attributes (like
nameor a customscore):g1 <- add_vertices(g1, 3, attr = list( name = c("NewNode1", "NewNode2", "NewNode3"), score = c(85, 92, 78) ))
Deleting Nodes
Use delete_vertices() to remove nodes. You can target nodes by their ID or attributes:
- Delete a node by its ID (e.g., delete the 2nd node):
g1 <- delete_vertices(g1, 2) - Delete nodes by an attribute (e.g., delete the node named "OldNode"):
Pro tip:g1 <- delete_vertices(g1, which(V(g1)$name == "OldNode"))V(g1)gives you access to all nodes in the graph, andwhich()helps you filter to the nodes you want to remove.
Getting Node Attributes/Associated Values
Access node attributes using V(g1) followed by the attribute name:
- Get all values of a specific attribute (e.g., all node names):
V(g1)$name - Get the value of an attribute for a single node (e.g., the
scoreattribute of the 1st node):V(g1)[1]$score - Get attributes for a node by name:
V(g1)[name == "NewNode1"]$score
Getting Edge Attributes/Associated Values
For edges, use E(g1) to access all edges, then reference the attribute you want (like weight for your weighted graph):
- Get all edge weights:
E(g1)$weight - Get the weight of a specific edge (e.g., from node 1 to node 3):
E(g1)[from(1) & to(3)]$weight - Get edge weight using node names instead of IDs:
E(g1)[from(V(g1)[name == "NewNode1"]) & to(V(g1)[name == "NewNode2"])]$weight
A quick sanity check after any operation: run summary(g1) to see the graph’s structure, node count, edge count, and attributes—it’s a great way to confirm everything worked as expected.
内容的提问来源于stack exchange,提问作者J.Cole

