Search code examples
rigraphundirected-graphedge-list

Counting undirected edges between any two nodes


I'm trying to generate an edge list to feed into R's igraph plotting function, which requires that I generate a data.frame' objective consisting of two columns representing "from" node and "to" node with other columns serving as edge attributes.

Since only an undirected graph is of interest here, I need to generate a dataframe of two columns consists of unique combination of any two nodes (no order) and generate the sum of all edges between them (again, undirected).

I referenced a number of earlier threads but cannot seem to get around with the count problem, because most codes treat A --> B and B <-- A as different pairs, for example:

library(igraph)
# generate 7 edge pairs
ee <- c("A", "B", "B", "A", "C", "A", "C", "D", "D", "E", "A", "E", "A", "C")
# convert to igraph object
g <- graph(ee)

# count edges

edge.count <- function(g){
     D <- data.frame(get.edgelist(g))  # convert to data frame
     ones <- rep(1, nrow(D))   # a column of 1s
     result <- aggregate(ones, by = as.list(D), FUN = sum)
     names(result) <- c("from", "to", "count")
     result
} 

count <- edge.count(g)

count
  from to count
1    B  A     1
2    C  A     1
3    A  B     1
4    C  D     1
5    A  E     1
6    D  E     1
7    A  C     1

But my desired output should have pair {B, A} with count of 2 and pair {C, A} with count of 2, since they are viewed as the same with pair {A, B} and {A, C} in an undirected graph.

Could someone recommend any way to solve this?


Solution

  • You can replace graph() with make_undirected_graph():

    g <- make_undirected_graph(ee)
    

    obtaining:

      from to count
    1    A  B     2
    2    A  C     2
    3    C  D     1
    4    A  E     1
    5    D  E     1
    

    Or even by:

    g <- graph(ee, directed = FALSE)