R:从图中减去子图

k10s72fa  于 2023-03-05  发布在  其他
关注(0)|答案(2)|浏览(136)

我有下面的网络图:

# 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中减去生成的子图。

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

of1yzvn4

of1yzvn41#

如果我没理解错的话,你可以从original_graph中减去neighbors图的名称,然后使用induced.subgraph函数创建所需的图。我不太清楚你在第3步中随机选择节点的意思,但也许你可以重复sample调用,但这次是从neighbors图开始。编辑-我添加了一些代码来完成这一操作。

vids <- unlist(ego(original_graph, order=radius, nodes=starting_node))
neighbors <- induced.subgraph(original_graph, vids = vids)
# find the names of the neighbors excluding the starting node
neighbor_names <- setdiff(V(neighbors)$name, starting_node)
# choose some random names - this won't work if the number of nodes is less than this - 3 for this example
random_neighbor_names <- sample(neighbor_names, 3)
# make a graph from the sampled names and the original
random_neighbors <- induced.subgraph(original_graph, vids=c(starting_node, random_neighbor_names))
# calculate the difference between the original and the random neighbors
remaining_names <- setdiff(V(original_graph)$name, V(random_neighbors)$name)
remaining <- induced.subgraph(original_graph, vids = remaining_names)
pwuypxnk

pwuypxnk2#

可以使用subgraphinduced.subgraph(作为Andrew Chisholm did

original_graph %>%
  subgraph(!V(.) %in% unlist(ego(., order = radius, nodes = starting_node)))

相关问题