igraph使用遇阻,如何编写循环批量处理个体网络分析统计?
个体网络统计量批量计算问题
需求
从包含数百个个体的地点检测数据集中,批量计算每个个体的三个网络统计量:
- 节点数:该个体访问的不同地点总数
- 边数:该个体在不同地点间的唯一连接数量(排除同地点的重复检测记录)
- 网络直径:该个体访问的任意两个地点之间的最大距离
数据集示例
生成简化数据集的代码
df <- data.frame(id = c("3811","3811","3832","3832","3832","3832"), Program = c("P1","P1","P1","P1","P1","P1"), from = c("hill","town","hill","wood","wood","lake"), from_lon = c(130.2,130.5,130.2,131.3,131.3,129.6), from_lat = c(-30.2,-30.5,-30.2,-31.3,-31.3,-29.6), to = c("town","lake","wood","wood","lake","town"), to_lon = c(130.5,129.6,131.3,131.3,129.6,130.5), to_lat = c(-30.5,-29.6,-31.3,-31.3,-29.6,-30.5), dist = c(44.111,132.506,161.456,0,249.847,132.506))
数据集内容
id Program from from_lon from_lat to to_lon to_lat dist 3811 P1 hill 130.2 -30.2 town 130.5 -30.5 44.111 3811 P1 town 130.5 -30.5 lake 129.6 -29.6 132.506 3832 P1 hill 130.2 -30.2 wood 131.3 -31.3 161.456 3832 P1 wood 131.3 -31.3 wood 131.3 -31.3 0.000 3832 P1 wood 131.3 -31.3 lake 129.6 -29.6 249.847 3832 P1 lake 129.6 -29.6 town 130.5 -30.5 132.506
当前手动实现
已编写代码可计算单个个体的统计量,但无法批量处理所有个体,代码如下:
# 计算个体3811的统计量 indiv_nodes <- df %>% filter(id == "3811"& dist > 0) %>% # 排除同地点重复检测 summarise( id = dplyr::first(id), prog = first(Program), nodes = n_distinct(to)+1, # +1包含起始地点 netdiam = max(dist)) indiv_edges <- df %>% filter(id == "3811" & dist > 0) %>% group_by(from, to) %>% summarise( from = dplyr::first(from), to = dplyr::first(to), weight = n()) net <- transform(indiv_nodes, edges = sum(indiv_edges$weight)) # 计算个体3832的统计量 indiv_nodes_n <- df %>% filter(id == "3832" & dist > 0) %>% summarise( id = dplyr::first(id), prog = first(Program), nodes = n_distinct(to)+1, netdiam = max(dist)) indiv_edges_n <- df %>% filter(id == "3832" & dist > 0) %>% group_by(from, to) %>% summarise( from = dplyr::first(from), to = dplyr::first(to), weight = n()) indiv_net <- transform(indiv_nodes_n, edges = sum(indiv_edges_n$weight)) net <- rbind(net, indiv_net) # 输出结果 net
运行结果
id prog nodes netdiam edges 3811 P1 3 132.506 2 3832 P1 4 249.847 3
求助点
数据集包含数百个个体,手动逐个处理效率极低,尝试编写循环函数未成功。希望得到以下任一解决方案:
- 使用
igraph包实现批量计算的代码 - 将现有代码改造为可遍历所有
id的批量处理函数
内容的提问来源于stack exchange,提问作者Boogaloo
相关产品推荐
相关产品推荐

