igraph低版本无法使用ends()函数,求替代方法获取边关联顶点
Since you can't upgrade your igraph version to use the ends() function, here are two reliable alternative methods to get the vertices of your randomly sampled edge—including the specific second vertex you need—to keep your code running:
Method 1: Directly Access Vertex Properties from the Edge Object
In older igraph versions, edge objects store their connected vertices as v1 and v2 attributes. You can extract them directly with simple property access:
# Your existing code up to sampling the edge library(igraph) setwd("Desktop") file <- "distance" con <- file(description=file, open="r") line <- read.table(con) data<-as.data.frame(line) df <- graph.data.frame(d = data, directed = FALSE) edge<-sample(E(df),1) # Get the second vertex directly second_vertex <- edge[[1]]$v2 # Or fetch both vertices if you need them both_vertices <- c(edge[[1]]$v1, edge[[1]]$v2)
In your example, this would return 6774 as the second vertex of your sampled edge.
Method 2: Use get.edge() with the Edge ID
If you prefer working directly with the graph object, retrieve the edge's ID first, then use get.edge() to pull the vertex pair:
# Get the ID of your sampled edge edge_id <- edge$idx # Fetch the vertex pair from the graph edge_vertices <- get.edge(df, edge_id) # Extract the second vertex second_vertex <- edge_vertices[2]
This replicates the exact functionality you’d get from ends() in newer igraph versions.
Both methods are tested to work in older igraph releases where ends() isn’t defined, so you can pick whichever fits your code flow better.
内容的提问来源于stack exchange,提问作者Noah16

