在R iGraph中包含一条边的三角形计数



iGraph可以使用igraph::count_triangles()计算包含每个顶点的三角形的数量。是否有一个类似的函数可以为边提供这个计数,或者有一种有效的方法来使用igraph::triangles()的输出来做到这一点?

我怀疑您可能必须自己实现它。下面的代码可能会给你一些提示

aggregate(
cnt ~ .,
cbind(
data.frame(
do.call(
rbind,
unlist(
apply(
matrix(triangles(kite), nrow = 3),
2,
function(x) combn(sort(x), 2, simplify = FALSE),
simplify = FALSE
),
recursive = FALSE
)
),
cnt = 1
)
), sum
)

subset(
as.data.frame(
table(
data.frame(
do.call(
rbind,
unlist(
apply(
matrix(triangles(kite), nrow = 3),
2,
function(x) combn(sort(x), 2, simplify = FALSE),
simplify = FALSE
),
recursive = FALSE
)
)
)
)
), Freq > 0)

给出如下的data.frame

X1 X2 cnt
1   1  2   1
2   1  3   2
3   1  4   3
4   2  4   3
5   3  4   2
6   2  5   2
7   4  5   2
8   1  6   2
9   3  6   2
10  4  6   3
11  2  7   2
12  4  7   3
13  5  7   2
14  6  7   2
15  6  8   1
16  7  8   1
<标题>虚拟数据
kite <- make_graph("Krackhardt_Kite")

我认为@ThomasIsCoding的代码中有一个错别字。具体来说,, simplify = FALSE)出现了两次。纠正这一点,并添加一些行来添加三角形计数作为igraph边缘权重给出:

triangles <- subset(as.data.frame(table(data.frame(do.call(rbind,unlist(apply(matrix(igraph::triangles(G), nrow = 3), 2, function(x) combn(sort(x), 2, simplify = FALSE)),recursive = FALSE))))), Freq > 0)
triangles$edge <- igraph::get.edge.ids(G, as.numeric(as.vector(unlist(t(triangles[,1:2])))))
igraph::E(G)$weight <- 0
igraph::E(G)$weight[triangles$edge] <- triangles$Freq[triangles$edge]

这看起来相当快,即使对于大的密集图也是如此。

最新更新