为什么我从图中得到错误的邻居

Why I am getting wrong neighbors from the graph

我正在尝试从图中找到节点的共同邻居。但是,node 8 我得到了 the wrong neighbor。从数据集中,我们可以说 node 8 的共同邻居是 node 5 and 6 但我得到 node 4 and 5!

代码:

graph <- graph_from_data_frame(df_graph, directed = FALSE)
plot(graph, vertex.label = V(graph)$name)
neighbors(graph, 8, mode="all")

输出:

+ 3/8 vertices, named, from a32ba25:
[1] 4 5 8

图表:

你能告诉我为什么我找错邻居了吗?

可重现的数据:

structure(list(To = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 4L, 5L, 8L, 
8L), From = c(7L, 3L, 4L, 7L, 4L, 5L, 4L, 6L, 6L, 5L, 6L)), class = "data.frame", row.names = c(NA, 
-11L))

区分顶点名称和顶点索引很重要。如果您使用数值,则表明您正在使用顶点索引。根据创建图形时数据的顺序,索引可能与名称不同。如果你 运行

V(graph)
# [1] 1 2 3 4 5 8 7 6

这会按索引顺序向您显示顶点的名称。所以第 8 个顶点实际上是顶点“6”。如果您想获得名称为“8”的顶点的邻居,那么您需要一个字符值。

neighbors(graph, "8", mode="all")
# [1] 5 6

如果您不使用数字作为顶点名称,这可能会更清楚。在您的 data.frame 中,您的 to 和 from 值可以是您喜欢的任何字符值。该图只会按照遇到它们的顺序为它们分配一个索引。如果您希望顶点按特定顺序排列。您可以使用 vertices= 参数

设置该顺序
graph <- graph_from_data_frame(df_graph, directed = FALSE, vertices=data.frame(name=1:8))