Zachary
Zachary

Reputation: 381

Counting triangles that include an edge in R iGraph

iGraph can count the number of triangles that include each vertex using igraph::count_triangles(). Is there a similar function that will provide this count for edges, or an efficient way to use the output from igraph::triangles() to do this?

Upvotes: 1

Views: 229

Answers (2)

Zachary
Zachary

Reputation: 381

I think there's a typo in @ThomasIsCoding's code. Specifically, , simplify = FALSE) appears twice. Correcting this, and adding a few lines to add the triangle counts as igraph edge weights gives:

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]

This seems to be fairly fast, even for large dense graphs.

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101247

I suspect that you may have to implement it by yourself. The code below might give you some hints

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
)

or

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)

which gives a data.frame like below

   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

Dummy Data

kite <- make_graph("Krackhardt_Kite")

Upvotes: 0

Related Questions