问题
I started using the R "igraph" package recently(version 0.7). I wrote a simple program to understand the basics of the package(reading data into the graph object, getting the neighbours of a node). I am using a graph whose vertices start at 0. The edges in the graph are populated as I need it, however when I attempt to get the adjacency list/ neighbours of a node, I observed it was not giving the result that I expected. Can someone help me out with this/ or point out if I am missing something trivial ?
Below is the graph data/code that I wrote:
Graph Edge Data(first column contains the first vertex, second column contain the vertex to which there is an edge from the first vertex)
0 5
1 5
2 5
3 5
0 2
> library('igraph')
> graph_file_ori = read.table("test.txt")
> graph_obj = graph.data.frame(graph_file_ori,directed=FALSE)
> str(graph_obj)
IGRAPH UN-- 5 5 --
+ attr: name (v/c)
+ edges (vertex names):
[1] 0--5 1--5 2--5 3--5 0--2
> neighbors(graph_obj,0)
Error in .Call("R_igraph_neighbors", graph, as.igraph.vs(graph, v) - 1, :
At type_indexededgelist.c:750 : cannot get neighbors, Invalid vertex id
> neighbors(graph_obj,1)
[1] 3 5
> neighbors(graph_obj,2)
[1] 5
> neighbors(graph_obj,3)
[1] 1 5
> neighbors(graph_obj,4)
[1] 5
> neighbors(graph_obj,5)
[1] 1 2 3 4
Based on the graph, the expected output was :
neighbors(0) = 5,2
neighbors(1) = 5
neighbors(2) = 5,0
neighbors(3) = 5
Degree of 4 is 0. Appreciate the help.
回答1:
Your graph has: vertex 1: "0", vertex 2: "1", vertex 3: "2", vertex 4: "3", vertex 5: "5"
Here is how I think neighbors() works:
neighbors(graph_obj, 1) <=> neighbors(graph_obj, vertex 1) and it returns vertex 3, vertex 5 <=> "2" , "5"
neighbors(graph_obj, 2) <=> neighbors(graph_obj, vertex 2) and it returns vertex 5 <=> "5"
neighbors(graph_obj, 3) <=> neighbors(graph_obj, vertex 3) and it returns vertex 1, vertex 5 <=> "0" , "5"
...
回答2:
If you want to use symbolic vertex names, that is fine, but then you need to use them in your queries as well. I.e. write
neighbors(graph_obj, "0")
If you want the results as symbolic names as well, then you need to do
graph_obj$name[neighbors(graph_obj, "0")]
This will be not needed from igraph version 0.8.
来源:https://stackoverflow.com/questions/26932407/issues-with-r-igraph-package-neighbor-function