Search code examples
rigraphcountingedges

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?


Solution

  • 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.