Mark
Mark

Reputation: 1769

Scale-Free graph, access the vertices of the graph

I'm trying to generate a Scale-Free graph, according to the Barabasi-Albert Model. I used the barabasi.game function, gerating 1000 vertices of the graph:

library('igraph')
g <- barabasi.game(1000)

I would like, now, to pick at random a vertex of g and, among its neighbors, to pick at random another vertex. How can I access the vertices of the graph?

Edit. I had problems with the solution kindly suggested by G5W. For this graph:

enter image description here

I obtained, from the first instruction

RV<-sample(V(g), 1)

the result RV=4, but from the second

RVn<-sample(neighbors(g, RV, mode="all"), 1)

I obtained RVn=1. As we can see from the pic this is a mistake; moreover, instruction

neighbors(g, i)

returns

+ 1/10 vertex, named, from 57207c1: 
[1] 2

Why?

Thank you.

Upvotes: 1

Views: 53

Answers (1)

G5W
G5W

Reputation: 37641

Modified

You can pick a random vertex and a random neighbor like this:

RV  = sample(V(g), 1)
NRV = neighbors(g, RV, mode="all")
RVn = ifelse(length(NRV) == 1, NRV, sample(NRV, 1))

This should work when RV has one neighbor or more.

I would like to mention that most vertices have only one neighbor, so the random selection of a neighbor doesn't do much.

table(sapply(V(g), function(v) length(neighbors(g, v, mode="all"))))
  1   2   3   4   5   6   7   8   9  10  11  12  13  14  18  21  37  38  92 
657 183  67  35  12  11   3   7   4   6   2   4   1   2   2   1   1   1   1 

Upvotes: 1

Related Questions