我是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个顶点?谢谢!
答案 0 :(得分: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)