You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将igraph的degree结果匹配到网络-人员配对数据框?

解决方案

核心思路

将所有igraph对象整理为命名列表(列表名对应网络名),批量计算每个网络的节点degree,生成包含网络名、人员名、degree的结果数据框,最后通过merge与all_pairs匹配合并,自动填充对应行的degree值。


步骤1:整理igraph对象为命名列表

首先将分散的igraph对象放入命名列表,列表名称与网络名(如mat1、mat2)一一对应,这是批量处理的基础:

# 把所有igraph对象放入命名列表,名称对应网络名
graph_list <- list(
  mat1 = mat1_graph,
  mat2 = mat2_graph,
  mat3 = mat3_graph
)

步骤2:定义批量处理函数

编写函数处理单个igraph对象,计算degree并返回带网络标识的数据框:

# 定义函数:计算指定网络的degree,返回结构化结果
calculate_degree <- function(graph, network_name) {
  # 计算all模式的degree(可根据需求修改mode参数,如"in"/"out")
  deg_values <- igraph::degree(graph, mode = "all")
  
  # 转换为数据框,names(deg_values)即为人员名称
  data.frame(
    network_name = network_name,
    person_name = names(deg_values),
    degree_all = as.numeric(deg_values),
    stringsAsFactors = FALSE
  )
}

步骤3:批量计算并合并结果

使用lapply遍历命名列表,批量处理所有igraph对象,再合并为统一的结果数据框:

# 批量处理所有网络,合并结果
degree_results <- do.call(rbind, lapply(names(graph_list), function(net_name) {
  calculate_degree(graph_list[[net_name]], net_name)
}))

# (可选)若安装了purrr包,可使用更简洁的写法:
# library(purrr)
# degree_results <- imap_dfr(graph_list, calculate_degree)

步骤4:匹配填充到all_pairs

通过merge左连接,将degree结果匹配到all_pairs的对应行:

# 左连接确保all_pairs的所有行都被保留,自动填充degree_all
all_pairs <- merge(all_pairs, degree_results,
                   by = c("network_name", "person_name"),
                   all.x = TRUE)

扩展:从矩阵批量转igraph对象(针对200个数据框场景)

如果你的200个数据是矩阵格式,可先将矩阵整理为命名列表,批量转换为igraph对象:

# 假设所有矩阵已放入命名列表mat_list
mat_list <- list(
  mat1 = mat1,
  mat2 = mat2,
  mat3 = mat3
)

# 批量转换为igraph对象
graph_list <- lapply(mat_list, function(mat) {
  graph_from_adjacency_matrix(mat, weighted = TRUE, mode = "directed", diag = FALSE)
})

效果验证

处理后all_pairs会新增degree_all列,例如:

print(all_pairs)
  network_name person_name degree_all
1         mat1      Carl.F          3
2         mat1     Chris.P          3
3         mat1     Haley.A          2
4         mat2     Chris.P          2
5         mat2       Tom.D          2
6         mat3      Carl.F          4
7         mat3   Charles.L          4
8         mat3     Peter.Q          3
9         mat3       Tom.D          3

内容的提问来源于stack exchange,提问作者poppiytt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 22:10:44