我有下面的网络图:
# Set the seed for reproducibility
set.seed(123)
# Generate a vector of ID's from 1 to 100
ids <- 1:100
# Initialize an empty data frame to store the "from" and "to" values
edges <- data.frame(from=integer(), to=integer(), stringsAsFactors=FALSE)
# Iterate through the ID's
for(id in ids) {
# Randomly select a minimum of 1 and a maximum of 8 neighbors for the current ID
neighbors <- sample(ids[ids != id], size=sample(1:8, size=1))
# Add a new row to the data frame for each "to" value
for(neighbor in neighbors) {
edges <- rbind(edges, data.frame(from=id, to=neighbor))
}
}
library(igraph)
library(visNetwork)
# Convert the data frame to an igraph object
original_graph <- graph_from_data_frame(edges, directed=FALSE)
我正在尝试完成以下过程:
- 第一步:从“original_graph”中随机选择“starting_node”
- 第二步:在0到3之间随机选择一个“半径”(即度)
- 步骤3:在这个随机“半径”的原始图(称为“子图”)中随机选择连接到“starting_node”的节点
- 步骤4:从“original_graph”中“减去”“子图”
下面是我尝试开始这个问题:
# step 1:
starting_node <- sample(V(original_graph), 1)$name
# step 2:
radius <- sample(0:3, 1)
# step 3:
neighbors <- induced.subgraph(original_graph, unlist(ego(original_graph, order=radius, nodes=starting_node)))
但是从这里开始--我不知道如何在starting_node周围随机构建子图,然后从original_graph中减去生成的子图。
有人能告诉我怎么继续吗?
谢谢!
2条答案
按热度按时间of1yzvn41#
如果我没理解错的话,你可以从
original_graph
中减去neighbors
图的名称,然后使用induced.subgraph
函数创建所需的图。我不太清楚你在第3步中随机选择节点的意思,但也许你可以重复sample
调用,但这次是从neighbors
图开始。编辑-我添加了一些代码来完成这一操作。pwuypxnk2#
可以使用
subgraph
或induced.subgraph
(作为Andrew Chisholm did)