使用tidygraph实现igraph批量节点子图分析的循环自动化
R语言igraph网络子图遍历自动化实现方案
实现逻辑说明
- 提取所有
job_type=1的节点作为源节点遍历池 - 对每个源节点按要求依次执行子图提取、孤立节点过滤、指标计算、符合条件结果归档操作
- 最终合并所有符合阈值要求的结果统一输出
完整可运行代码
# 加载依赖包 library(igraph) library(dplyr) # 初始化结果存储容器 final_result <- data.frame() # 提取所有job_type=1的源节点ID列表 source_nodes <- V(tp_network_subset)$job_id[V(tp_network_subset)$job_type == 1] # 遍历所有源节点执行流程 for (src_id in source_nodes) { # 提取当前源节点的1阶邻居子图(包含源节点本身) src_vid <- which(V(tp_network_subset)$job_id == src_id) ego_g <- make_ego_graph(tp_network_subset, order = 1, nodes = src_vid)[[1]] # 过滤子图中的孤立节点(度为0的节点) g_degree <- degree(ego_g) filtered_g <- delete_vertices(ego_g, which(g_degree == 0)) # 过滤后子图为空则跳过当前源节点 if (vcount(filtered_g) == 0) next # 计算job_rate指标 node_types <- V(filtered_g)$job_type cnt_type1 <- sum(node_types == 1) cnt_valid <- sum(node_types %in% c(1,2,3)) # 增加除零错误规避逻辑 if (cnt_valid == 0) next job_rate <- cnt_type1 / cnt_valid # 符合阈值要求则提取目标节点并归档 if (job_rate > 0.5) { # 提取子图中job_type=0的节点属性 type0_nodes <- as.data.frame(vertex_attr(filtered_g)) %>% filter(job_type == 0) # 附加子图统计字段 type0_nodes <- type0_nodes %>% mutate( source_job_id = src_id, job_rate = job_rate, subgraph_total_cnt = vcount(filtered_g), cnt_type1 = cnt_type1, cnt_type2 = sum(node_types == 2), cnt_type3 = sum(node_types == 3), cnt_type0 = sum(node_types == 0) ) # 合并到全局结果表 final_result <- bind_rows(final_result, type0_nodes) } } # 输出最终合并结果 View(final_result)
结果字段说明
- 基础节点字段:保留原始节点表的
job_id、job_type等所有自定义属性 - 统计附加字段:
source_job_id:当前子图对应的源节点IDjob_rate:当前子图的job_rate指标计算值subgraph_total_cnt:过滤孤立节点后子图的总节点数cnt_type0/cnt_type1/cnt_type2/cnt_type3:子图内对应job_type的节点数量
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

