微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 igraph

如何解决使用 igraph

我正在处理一个图表,其中每个节点都有以下属性“组”:“婴儿产品”、“书籍”“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 个元素的边缘列表上快速执行此操作。

非常感谢您。

解决方法

我认为使用 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。