R语言 创建随机连通子图

pu3pd22g  于 2023-03-15  发布在  其他
关注(0)|答案(2)|浏览(154)

bounty将在3天后过期。回答此问题可获得+50的声誉奖励。stats_noob正在寻找来自声誉良好来源的答案

我在R中创建了这个随机图/网络:

set.seed(123)
library(igraph)

# Create random graph
graph <- erdos.renyi.game(21, 0.3, type=c("gnp", "gnm"), directed = FALSE, loops = FALSE)

然后,我尝试创建一个随机连通子图:

# Get the edges of the random subgraph
random_edges <- sample(E(graph), 10)

# Create subgraph from the random edges
subgraph <- subgraph.edges(graph, random_edges)

par(mfrow = c(1,2))

# Plot the subgraph
plot(subgraph, main = "random subgraph")
plot(graph, main = "original graph")

**我的问题:**当我查看随机子图时,我看到“节点4”连接到“节点10”-但在原始图中,“节点4”和“节点10”彼此不连接。

有人能告诉我怎么修吗?
谢谢!

tp5buhyn

tp5buhyn1#

如果你想有一个使用subgraph.edges的子图,你应该有id:
将保留在结果图形中的边的边ID。
可以使用V获取顶点的ID,如下所示:

set.seed(123)
library(igraph)

# Create random graph
graph <- erdos.renyi.game(21, 0.3, type=c("gnp", "gnm"), directed = FALSE, loops = FALSE)

# Get the edges of the random subgraph
# random_edges <- sample(E(graph), 10)
random_vertices <- sample(V(graph), 10)

# Create subgraph from the random edges
subgraph <- subgraph.edges(graph, random_vertices)

par(mfrow = c(1,2))

# Plot the subgraph
plot(subgraph, main = "random subgraph")
plot(graph, main = "original graph")

创建于2023年3月11日,使用reprex v2.0.2

kxeu7u2r

kxeu7u2r2#

我认为一个解决方法是**在执行induced.subgraph**之前给顶点添加一个name属性。否则,顶点“标签”(将显示在子图的绘图中)将被不同地索引,而不是在原始graph中保持相同的vid
例如,您可以执行以下操作

graph %>%
  set.vertex.attribute(name = "name", value = V(.)) %>%
  induced.subgraph(unique(c(ends(., random_edges))))

那么你将得到如下的子图

IGRAPH da87a26 UN-- 10 16 -- Erdos-Renyi (gnp) graph
+ attr: name (g/c), type (g/c), loops (g/l), p (g/n), name (v/n)
+ edges from da87a26 (vertex names):
 [1]  5--10  1--14  3--14  1--15 14--15  3--16 14--16 14--17  1--18  5--18
[11] 14--18 15--18 17--18  3--20 10--20 16--20

相关问题