Search code examples
redges

Is there an R function to get the unique edges in an undirected (not directed) network?


I want to count the number of the unique edges in an undirected network, e.g, net

   x  y
1  A  B
2  B  A
3  A  B

There should be only one unique edge for this matrix, because edges A-B and B-A are same for the undirected network.

For the directed network I can get the number of unique edges by:

nrow(unique(net[,c("x","y"]))

But this doesn't work for the undirected network.


Solution

  • Given that you are working with networks, an igraph solution:

    library(igraph)
    
    as_data_frame(simplify(graph_from_data_frame(dat, directed=FALSE)))
    

    Then use nrow


    Explanantion

    dat %>% 
      graph_from_data_frame(., directed=FALSE) %>% # convert to undirected graph
      simplify %>%                                 # remove loops / multiple edges
      as_data_frame                                # return remaining edges