r - 如何迭代地定义映射参数以收缩顶点链?
问题描述
我有一个简单的图表g
。需要通过删除度数为2的顶点来平滑图,同时保留原始图的布局。在 Mathematica中解决了相同的任务。
library(igraph)
set.seed(1)
# preprocessing
g <- sample_gnp(40, 1/20)
V(g)$name <- seq(1:vcount(g))
components <- clusters(g, mode="weak")
biggest_cluster_id <- which.max(components$csize)
vert_ids <- V(g)[components$membership == biggest_cluster_id]
vert_ids
# input random graph
g <- induced_subgraph(g, vert_ids)
LO = layout.fruchterman.reingold(g)
plot(g, vertex.color = ifelse(degree(g)==2, "red", "green"), main ="g", layout = LO)
我选择了度数为 2 的顶点链。
subg <- induced_subgraph(g, degree(g)==2)
subg_ids <- V(subg); subg_ids
我已阅读问答并手动定义函数的mapping
参数contract()
。
# join nodes 3 -> 14, 15 -> 40, 13 -> 31, 29 -> 6
mapping = c(2, 3, 4, 5, 6, 7, 8, 10, 13, 3, 15, 16, 17, 18, 19, 20, 21, 22, 23, 25, 26, 27, 6, 30, 13, 32, 33, 34, 35, 36, 38, 39, 15)
g2 <- simplify(contract(g, mapping=mapping, vertex.attr.comb=toString))
# L2 <- LO[-as.numeric(c(14, 40, 31, 6)),] # not working
plot(g2, vertex.color = ifelse(degree(g2)==2, "red", "green"), main ="g2")
问题。mapping
迭代定义参数的可能方法是什么?
解决方案
这只是部分答案,因为它没有提供自动计算收缩的方法。但是,我可以对手动映射提供一些见解:
您的顶点有名称,因此这些名称用于参考,而不是从 1 到 n 的内部顶点编号。在映射中,我们需要给出收缩后顶点的新 ID。
原来的ID是
> V(g)
+ 33/33 vertices, named, from 0af52c3:
[1] 2 3 4 5 6 7 8 10 13 14 15 16 17 18 19 20 21 22 23 25 26 27 29 30 31 32 33 34 35 36 38 39 40
新的 ID 可以给出(存在多种可能性):
mapping <- c(6, 14, 6, 5, 6, 7, 7, 10, 31, 14, 15, 16, 17, 14, 6, 7, 31, 22, 6, 25, 26, 27, 14, 30, 31, 6, 6, 34, 35, 36, 38, 39, 15)
为了更好地概述:
old ID: 2 3 4 5 6 7 8 10 13 14 15 16 17 18 19 20 21 22 23 25 26 27 29 30 31 32 33 34 35 36 38 39 40
new ID: 6 14 6 5 6 7 7 10 31 14 15 16 17 14 6 7 31 22 6 25 26 27 14 30 31 6 6 34 35 36 38 39 15
这导致:
g2 <- simplify(contract(g, mapping=mapping, vertex.attr.comb=toString))
plot(g2, vertex.color = ifelse(degree(g2)==2, "red", "green"), main ="g2")
要摆脱现有的 degree-0-nodes,您可以执行以下操作:
g3 <- delete.vertices(g2, which(degree(g2) == 0))
或者,甚至更干净,您可以删除无名节点:
g3 <- delete.vertices(g2, which(names(V(g2)) == ""))
要保留原始布局,您可以执行以下操作:
L3 <- LO[-which(mapping != as.numeric(names(V(g)))),]
plot(g3, layout = L3)
但是在这种情况下不是很好看...
推荐阅读
- r - 从 anova 访问多个因变量的 pvalue 并将结果存储在文档 txt 中
- sql - 尝试在 LiveSQL 中创建表时标识符无效
- javascript - nomodule 和 "type="module" 对于 IE 11 的工作方式不同
- command-line - 管理安装 - 控制输出
- camunda - Camunda 无法从丢失的数据库连接中恢复
- windows - 不能将不兼容的 Qt 库(版本 0x50c05)与此库(版本 0x50c06)混合
- c# - 通过 Excel 互操作进行一系列复制/粘贴后,OpenClipboard 失败(HRESULT:0x800401D0)
- c# - Create/Alter 过程必须是查询批处理中的第一条语句
- vue.js - Vuejs - 将道具(从对象)传递给孩子并返回给父母
- cron - Openshift/Kubernetes 中的 Pod 调度