簡體   English   中英

如何從R中的圖形隨機選擇2個頂點?

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

我是R的新手,並嘗試從圖形中隨機選擇2個頂點。

到目前為止,我要做的是:首先,建立一個圖表

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

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

smalledges.csv是一個如下所示的文件:

from     to
4327231  2587908

然后,我將圖中的所有頂點放入一個列表中:

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

之后,我嘗試使用:

sample(vList, 2)

但是我得到的是一個錯誤:

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

我猜是因為R認為我想要的是2個隨機列表,所以我嘗試了以下方法:

sample(vList, 2, replace = TRUE)

然后,我有2個大列表...但是那不是我想要的! 伙計們,如何從圖形中隨機選擇2個頂點? 謝謝!

從您的問題中不清楚,您是否只需要這些頂點或包含這些頂點的子圖。 這是兩個例子。

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