Home > database >  Create edgelist that contains mutual dyads
Create edgelist that contains mutual dyads

Time:06-03

I have an edgelist where I want to keep dyads that mutually selected each other (e.g., 1 -> 4 and 4 -> 1). However, in the final edgelist I only want to keep one row instead of both rows of the mutual dyads (e.g., only row 1 -> 4 not both rows 1 -> 4 and 4 -> 1). How do I achieve that?

Here is the dataset:

library(igraph)
ff <- as_data_frame(sample_gnm(10, 50, directed=TRUE))
ff
   from to
1     1 10
2     1  3
3     1  4
4     1  5
5     1  6
6     1  7
7     1  8
8     2  1
9     2  3
10    2  8
11    2  9
12    3  1
13    3  2
14    3 10
15    3  4
16    3  5
17    3  6
18    3  8
19    3  9
20    4  3
21    4 10
22    5  1
23    5  2
24    5  3
25    5  4
26    6  2
27    6  3
28    6  4
29    6  5
30    7  3
31    7  5
32    7  6
33    7 10
34    7  8
35    8  1
36    8  2
37    8  4
38    8  5
39    8 10
40    9  1
41    9  2
42    9  3
43    9  4
44    9  5
45    9  7
46   10  1
47   10  3
48   10  4
49   10  8
50   10  9
cd <- which_mutual(g) #I know I can use `which_mutual` to identify the mutual dyads
ff[which(cd==1),] #but in the end this keeps both rows of the mutual dyads (e.g., 1 -> 4 and 4 -> 1)
       from to
    4     1  4
    6     1  6
    7     1  7
    9     2 10
    10    2  3
    14    3  2
    18    3  6
    21    4  1
    25    5 10
    28    6  1
    30    6  3
    32    6 10
    33    6  7
    34    7  1
    37    7  6
    39    7  8
    42    8  7
    45    9 10
    46   10  2
    47   10  5
    48   10  6
    50   10  9

CodePudding user response:

We may use duplicated to create a logical vector after sorting the elements by row

ff1 <- ff[which(cd==1),]
subset(ff1, !duplicated(cbind(pmin(from, to), pmax(from, to))))
  • Related