【发布时间】:2023-11-05 03:24:01
【问题描述】:
我正在尝试使用基于规则的 igraph 在 R 中创建一个图形。我有一个带有节点的图,每个节点都有几个属性。我想根据这些属性添加边缘。玩具示例:
library(igraph)
make_empty_graph() %>%
add_vertices(
nv = 5,
attr = list(
this_attr = sample(c("a", "b"), 5, replace = TRUE)
)
) %>%
{something here to add edges where this_attr is the same)
如果我在 Python 中使用 Gremlin,这似乎是一个解决方案,但我对它/igraph 的理解不足以转换为 igraph:Gremlin: adding edges between nodes having the same property
如果 tidygraph 能让这更容易,那将是一个可接受的依赖项。
任何帮助将不胜感激。
编辑:这可行,但感觉超级混乱。
g <- igraph::make_empty_graph() %>%
igraph::add_vertices(
nv = 5,
attr = list(
sample_attr = sample(c("a", "b"), 5, replace = TRUE)
)
)
g %>%
igraph::vertex_attr() %>%
unname() %>%
purrr::map(
function(this_attribute) {
unique(this_attribute) %>%
purrr::map(
function(this_value) {
utils::combn(
which(this_attribute == this_value), 2
) %>%
as.integer()
}
) %>% unlist()
}
) %>%
unlist() %>%
igraph::add_edges(g, .)
类似但更干净的东西会很棒。
【问题讨论】: