【问题标题】:Contract verticies by attribute with igraph使用 igraph 按属性收缩顶点
【发布时间】:2021-09-04 10:04:40
【问题描述】:

我正在处理一个图表,其中每个节点都有一个属性“组”,包括以下内容:“婴儿产品”、“书籍”“CE”“DVD”“音乐”“软件”“玩具”“视频”“电子游戏”。

我想知道如何绘制代表这些社区的图:应该有 9 个顶点,每个组一个,并且每次连接两个类别的两个节点时都有一个链接(可能加权)。

我曾尝试使用 igraph 合约功能,但结果如下:

> contract(fullnet, mapping=as.factor(products$group), vertex.attr.comb = products$group)
Error in FUN(X[[i]], ...) : 
  Unknown/unambigous attribute combination specification
Inoltre: Warning message:
In igraph.i.attribute.combination(vertex.attr.comb) :
  Some attributes are duplicated

我想我误解了这个函数的用途。

现在我正在考虑创建一个新的边缘列表,与之前的一样,但不是每个顶点的 Id 而是组的名称。可悲的是,我不知道如何在超过 1200000 个元素的边缘列表上快速执行此操作。

非常感谢您。

【问题讨论】:

  • 请提供一个完整的自包含的可重现示例,包括所有数据、代码以及可能的预期输出。

标签: r graph igraph social-networking


【解决方案1】:

我认为使用contract() 应该是正确的。在下面的示例代码中,我向vertex.attr.comb 添加了一个匿名函数,以通过group 组合顶点。然后,simplify() 去除循环边缘并计算边缘权重之和。

# Create example graph
set.seed(1)
g <- random.graph.game(10, 0.2)
V(g)$group <- rep(letters[1:3], times = c(3, 3, 4))
E(g)$weight <- 1:length(E(g))
E(g)
# + 9/9 edges from 7017c6a:
#   [1] 2-- 3 3-- 4 4-- 7 5-- 7 5-- 8 7-- 8 3-- 9 2--10 9--10
E(g)$weight
# [1] 1 2 3 4 5 6 7 8 9

# Contract graph by `group` attribute of vertices
g1 <- contract(g, factor(V(g)$group),
               vertex.attr.comb = function(x) levels(factor(x)))
# Remove loop edges and compute the sum of edge weight by group
g1 <- simplify(g1, edge.attr.comb = "sum")
E(g1)
# + 3/3 edges from a852397:
#   [1] 1--2 1--3 2--3
E(g1)$weight
# [1]  2 15 12

【讨论】:

    猜你喜欢
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 2016-05-28
    相关资源
    最近更新 更多