简体   繁体   中英

How to randomly select 2 vertices from a graph in R?

I'm new to R, and I'm trying to randomly select 2 vertices from a graph.

What I've done so far is: First, set up a graph

edgePath <- "./project1/data/smalledges.csv"

edgesMatrix <- as.matrix(read.csv(edgePath, header = TRUE, colClasses = "character"))
graph <- graph.edgelist(edgesMatrix)

The smalledges.csv is a file look like this:

from     to
4327231  2587908

Then I get all the vertices from the graph into a list:

vList <- as.list(get.data.frame(graph, what = c("vertices")))

After that, I try to use:

sample(vList, 2)

But what I've got is an error:

cannot take a sample larger than the population when 'replace = FALSE'

I guess it's because R thinks what I want is 2 random lists, so I tried this:

sample(vList, 2, replace = TRUE)

And then I've got 2 large lists... BUT THAT'S NOT WHAT I WANTED! So guys, how can I randomly select 2 vertices from my graph? Thanks!

Not clear from your question whether you want just the vertices, or a sub-graph containing those vertices. Here's an example of both.

library(igraph)
set.seed(1)    # for reproducible example
g <- erdos.renyi.game(10, 0.3)

par(mfrow=c(1,3), mar=c(1,1,1,1))
set.seed(1)    # for reproducible plot
plot(g)
# random sample of vertices
smpl <- sample(1:vcount(g),5)    
V(g)[smpl]                      # 5 random vertices
# Vertex sequence:
# [1] 9 5 7 2 4

# change the color of only those vertices
V(g)[smpl]$color="lightgreen"   # make them light green
set.seed(1)    # for reproducible plot
plot(g)
# create a sub-graph with only those vertices, retaining edge structure
sub.g <- induced.subgraph(g,V(g)[smpl])
plot(sub.g)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM