我在 R 中有这张图:
library(igraph)
set.seed(123)
n <- 20
g <- sample_gnm(n, m = n * 2, directed = FALSE)
while (!is_connected(g)) {
# Find disconnected components
components <- components(g)
for (i in 2:components$no) {
from <- sample(which(components$membership == i), 1)
to <- sample(which(components$membership == 1), 1)
g <- add_edges(g, c(from, to))
}
}
g <- simplify(g, remove.multiple = FALSE, remove.loops = TRUE)
V(g)$weight <- runif(vcount(g))
layout <- layout_with_fr(g)
plot(g, layout = layout, edge.arrow.size = 0.1,
vertex.label = V(g)$name, vertex.size = 15,
vertex.label.color = "black", edge.curved = 0,
vertex.color = "white", edge.color = "black")
我想找出周边所有节点的列表。
我尝试这样做(我读到了
eccentricity
函数):
library(igraph)
find_outer_nodes <- function(g) {
eccentricities <- eccentricity(g)
diameter <- max(eccentricities)
outer_nodes <- which(eccentricities == diameter)
return(outer_nodes)
}
outer_nodes <- find_outer_nodes(g)
print(outer_nodes)
答案如下:
[1] 2 3 7 13 16 18 19 20
在 R 中是否有更直接的方法来做到这一点?
使用
distances
> V(g)[sort(unique(c(which(distances(g) == diameter(g), TRUE))))]
+ 8/20 vertices, from d1b927a:
[1] 2 3 7 13 16 18 19 20