如何从 R 中的图中随机 select 2 个顶点?
How to randomly select 2 vertices from a graph in R?
我是 R 的新手,我正在尝试从图中随机 select 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 个大列表...但这不是我想要的!伙计们,我怎样才能从我的图中随机 select 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)
我是 R 的新手,我正在尝试从图中随机 select 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 个大列表...但这不是我想要的!伙计们,我怎样才能从我的图中随机 select 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)