NBK
NBK

Reputation: 905

Create edgelist from graph, with all potential combinations of vertices

I want to convert a graph into an edgelist. This can be done with the get.edgelist function. The problem is that this function only produces edgelist connections between connected nodes. I need an edgelist with all potential combinations of nodes, not only the connected ones. Take the following example:

set.seed(1234)
g <- sample_gnm(n=20,m=20)
E(g)$weight <- sample(20)
plot(g)

enter image description here

Now I create an edgelist that includes the weigths of each connection in the third column.

cbind(get.edgelist(g,names=TRUE),E(g)$weight)

      [,1] [,2] [,3]
 [1,]    3    5    4
 [2,]    1    7   11
 [3,]    1    8   16
 [4,]    3    9    8
 [5,]    1   10   12
 [6,]    4   10    1
 [7,]    7   12    7
 [8,]    2   13   10
 [9,]    6   13   14
[10,]   11   14    2
[11,]    3   15    3
[12,]   14   15   13
[13,]    2   16    9
[14,]   15   16   17
[15,]    1   17    5
[16,]   11   17   20
[17,]    6   18    6
[18,]    2   19   18
[19,]   14   19   15
[20,]   14   20   19

This result is not satisfactory, because it gives me the actual combinations of nodes but not all the potential combinations of nodes. For example, nodes 4 and 5 aren't connected in the graph, so don't appear in the same row of the edgelist. In an ideal world, I would get all potential combinations, including nodes 4 and 5, with a edge weight zero in the third column. Anyone?

Upvotes: 1

Views: 523

Answers (1)

Roman
Roman

Reputation: 17648

You can try a tidyverse using complete for continous data and fill V3 with 0's. Finally filter out "self-edges".

library(tidyverse)
cbind(get.edgelist(g,names=TRUE),E(g)$weight) %>% 
  as.tibble() %>% 
  complete(V1=1:20, V2=1:20, fill = list(V3 = 0)) %>% 
  filter(V1 != V2)
# A tibble: 380 x 3
      V1    V2    V3
   <dbl> <dbl> <dbl>
 1     1     2     0
 2     1     3     0
 3     1     4     0
 4     1     5     0
 5     1     6     0
 6     1     7     0
 7     1     8    13
 8     1     9     0
 9     1    10     0
10     1    11     0
# ... with 370 more rows

Upvotes: 1

Related Questions