Search code examples
rigraphsocial-networking

Get out degree indice for both vertices on the edge_list and out the indices on separate dataframe columns


I used degree() function from igraph package to calculate out degree indices for both vertices on an edge for a small example edge list of 7 unique edges, and I am wondering how can I render those out degree indices into two separate columns for both vertices on the same unique edge, below is my example code:

library(igraph)
g <- graph.formula(1-2-3-4, 2-5, 3-6, 2-4-7)
degs <- degree(g, mode = "out")

The desired output should look like this

from	to	from_out	to_out
1	    2	     1	      4
2	    3	     4	      3 
3	    4      3	      3 
2	    5	     4	      1
3	    6	     3	      1
2	    4	     4	      3 
4	    7	     3	      1

It will be really appreciated if someone could shed some light on this.


Solution

  • #turn graph to data.frame
    DF <- as_data_frame(g)
    
    #degs is a named vector
    DF$from_out <- degs[as.character(DF$from)]
    DF$to_out <- degs[as.character(DF$to)]
    #  from to from_out to_out
    #1    1  2        1      4
    #2    2  3        4      3
    #3    2  4        4      3
    #4    2  5        4      1
    #5    3  4        3      3
    #6    3  6        3      1
    #7    4  7        3      1