Reputation: 53
First of all I want to say that I already read answers for the question: "issues with R “igraph” package neighbor function" and I tried to solve my problem but I couldn't. I tried to ask my question as follow up comment but because of low level of reputation I couldn't, therefore I open this new question. Now here is my question: I have the same problem with neighbors function as it has been explained in: "igraph” package neighbor function but when I try the solution which is given by Gabor Csardi I just received null as result. I attached that part of my code here as well. I would be really thankful for any help and answer. my table:
edgelist <- read.table(text = "
1 2
2 3
3 4
4 5
3 6
6 7")
library(igraph)
graph <- graph.data.frame(edgelist)
str(graph)
## IGRAPH DN-- 7 6 --
## + attr: name (v/c)
## + edges (vertex names):
## [1] 1->2 2->3 3->4 4->5 3->6 6->7
now if I want the neighbors of the node 3 it should be
2, 4, 6
but the result I got is:
2, 4, 5
I noticed it changed the order of my nodes. As I explained before I try the solution that I found in stack overflow but I got null as result:
graph$name[neighbors(graph, 3)]
NULL
I don't know what else I can do, I would appreciate any help.
Upvotes: 4
Views: 6583
Reputation: 10223
Before we begin, you should be careful to not confused the label/name and the index/number of a given vertex. When you use both numbers for labels and indicies things quickly become confusing. To avoid all confusion, I've here used letters
edgelist <- read.table(text = "
A B
B C
C D
D E
C F
F G")
library(igraph)
graph <- graph.data.frame(edgelist)
str(graph)
#IGRAPH DN-- 7 6 --
# + attr: name (v/c)
# + edges (vertex names):
# [1] A->B B->C C->D D->E C->F F->G
To see what were dealing with, we plot it:
plot(graph)
To get the index of the neighbors do something like:
(remember there is a mode
argument)
neighbors(graph, 3, mode = "total") # Index of neighbours by index
## [1] 2 4 5
neighbors(graph, "C", mode = "total") # Index of neighbours by label
## [1] 2 4 5
To do what Gabor suggests you need to do the following. (I think he missed V( )
and wrote graph$name
when he meant V(graph)$name
in his post)
# Label of neighbours by label
V(graph)$name[neighbors(graph, "C", mode = "total")]
## [1] "B" "D" "F"
This gives the labels of the corresponding "neighbors". Which does agree with the image.
EDIT Oops. I messed up. Used E()
instead of V()
. It seems to work as intended. Sorry.
EDIT 2 To see a plot of the neighbors (induced subgraph) you can do something like:
n <- neighbors(graph, "C", mode = "total")
subgraph <- induced.subgraph(graph, n)
plot(subgraph)
In this case, a rather boring subgraph. You might want to include the vertex in question as well:
subgraph2 <- induced.subgraph(graph, c(n, V(graph)["C"]))
plot(subgraph2)
Upvotes: 9
Reputation: 499
Or, you can use which to give you the index you want:
neighbors(g,which(V(g)$name %in% 'A'),mode='in')
Upvotes: 0