Reputation: 755
I am trying to find the common neighbor of a node from a graph. But, I am getting the wrong neighbor
for node 8
. From the dataset, we can say the common neighbor for the node 8
are node 5 and 6
but I am getting node 4 and 5
!
Code:
graph <- graph_from_data_frame(df_graph, directed = FALSE)
plot(graph, vertex.label = V(graph)$name)
neighbors(graph, 8, mode="all")
Output:
+ 3/8 vertices, named, from a32ba25:
[1] 4 5 8
Graph:
Could you tell me why I am getting the wrong neighbor?
Reproducible Data:
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))
Upvotes: 2
Views: 115
Reputation: 206167
It's important to make the distinction between vertex names and vertex indexes. If you use a numeric value, that indicates you are using vertex indexes. Depending on the order of your data when you create the graph, then index may not be the same as the name. If you run
V(graph)
# [1] 1 2 3 4 5 8 7 6
That shows you the names of the vertices in index order. So the 8th vertex is actually vertex "6". If you want to get the neighbors for the vertex with the name "8", then you a character value.
neighbors(graph, "8", mode="all")
# [1] 5 6
This might have been more clear had you not used numbers for vertex names. In your data.frame, your to and from values can be any character values you like. The graph will just assign them an index in the order in which they are encountered. If you want the vertices to be in a specific order. You can set that order with the vertices=
parameter
graph <- graph_from_data_frame(df_graph, directed = FALSE, vertices=data.frame(name=1:8))
Upvotes: 5