[英]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.