如何从R中的图中随机选择2个顶点?
我是R新手,我尝试从图中随机选择两个顶点 到目前为止,我所做的是: 首先,建立一个图表如何从R中的图中随机选择2个顶点?,r,random,igraph,R,Random,Igraph,我是R新手,我尝试从图中随机选择两个顶点 到目前为止,我所做的是: 首先,建立一个图表 edgePath <- "./project1/data/smalledges.csv" edgesMatrix <- as.matrix(read.csv(edgePath, header = TRUE, colClasses = "character")) graph <- graph.edgelist(edgesMatrix) 然后,我将图形中的所有顶点放入一个列表: vList
edgePath <- "./project1/data/smalledges.csv"
edgesMatrix <- as.matrix(read.csv(edgePath, header = TRUE, colClasses = "character"))
graph <- graph.edgelist(edgesMatrix)
然后,我将图形中的所有顶点放入一个列表:
vList <- as.list(get.data.frame(graph, what = c("vertices")))
但我得到的是一个错误:
cannot take a sample larger than the population when 'replace = FALSE'
我想这是因为R认为我想要的是两个随机列表,所以我尝试了以下方法:
sample(vList, 2, replace = TRUE)
然后我有两个大的列表。。。但那不是我想要的!伙计们,我怎么能从我的图中随机选择两个顶点呢?谢谢 您的问题不清楚您想要的是顶点,还是包含这些顶点的子图。这里有两个例子
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)
只是一个猜测-samplevList[[1]],2。更直接地说,sampleVgraph$name,2,replace=FALSE,其中replace=FALSE确保将选择两个不同的顶点。谢谢!这正是我需要的!如何确保顶点的名称是正确的?
sample(vList, 2, replace = TRUE)
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)