基于tidygraph按年份计算节点的特征向量与度中心性
用tidygraph生成节点-年度中心性数据集
需求:使用R 4.2.2版本与tidygraph 1.2.3处理网络数据,无需筛选、合并或循环操作,直接生成包含各节点每年特征向量中心性和度中心性的节点-年度数据集。
解决方案
核心思路是利用tidygraph的group_graphs()函数按年份拆分网络为年度子图,再在每个子图上计算节点中心性,最后自动合并结果。
完整代码
library(tidyverse) library(tidygraph) # 生成节点和边数据 nodes <- tibble( node_id = 1:6, transaction_type = c("Purchase", "Deposit", "Withdrawal", "Transfer", "Payment", "Loan") ) edges <- tibble( from = c(1, 2, 3, 2, 4, 4, 5, 6, 5), to = c(2, 4, 2, 3, 5, 6, 6, 4, 1), year = c(2019, 2020, 2019, 2018, 2021, 2020, 2022, 2021, 2018), amount = c(100, 500, 50, 200, 300, 150, 75, 1000, 250) ) # 转换为tidygraph并生成节点-年度中心性数据 net_tidy <- as_tbl_graph(edges, vertices = nodes, directed = TRUE) node_year_centrality <- net_tidy %>% group_graphs(year) %>% # 按边的year字段拆分为年度子图 map_dfr(function(subgraph) { subgraph %>% activate(nodes) %>% mutate( year = subgraph %>% activate(edges) %>% pull(year) %>% first(), degree_centr = centrality_degree(), # 计算度中心性 eigen_centr = centrality_eigen(directed = TRUE) # 计算特征向量中心性(适配有向图) ) %>% as_tibble() }) # 查看结果 node_year_centrality
代码说明
group_graphs(year):将原网络按边的year属性拆分为多个独立的年度子图,每个子图仅包含对应年份的边。map_dfr():遍历每个年度子图,计算节点的度中心性和特征向量中心性,同时将年份信息添加到节点数据中,最后按行合并所有子图的结果。- 无需手动循环或筛选,全程通过tidygraph的管道操作完成,符合需求。
内容的提问来源于stack exchange,提问作者Livio Miles Silva Müller
相关产品推荐
相关产品推荐

