简体   繁体   English

如何从R中的图形随机选择2个顶点?

[英]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. 我是R的新手,并尝试从图形中随机选择2个顶点。

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: smalledges.csv是一个如下所示的文件:

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: 我猜是因为R认为我想要的是2个随机列表,所以我尝试了以下方法:

sample(vList, 2, replace = TRUE)

And then I've got 2 large lists... BUT THAT'S NOT WHAT I WANTED! 然后,我有2个大列表...但是那不是我想要的! So guys, how can I randomly select 2 vertices from my graph? 伙计们,如何从图形中随机选择2个顶点? 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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