【问题标题】:Counting triangles that include an edge in R iGraph计算 R iGraph 中包含边的三角形
【发布时间】:2021-10-06 04:02:46
【问题描述】:

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

【问题讨论】:

    标签: r igraph counting edges


    【解决方案1】:

    我认为@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]
    

    这似乎相当快,即使对于大型密集图也是如此。

    【讨论】:

      【解决方案2】:

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

      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")
      

      【讨论】:

        猜你喜欢
        • 2018-01-09
        • 2021-06-28
        • 2013-09-10
        • 1970-01-01
        • 2017-06-30
        • 2014-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多