Make an edgelist from a set of input objects. This function doesn't do anything that igraph or network/sna can't also already do. The usefulness of this function is its consistent API.

to_edgelist(x, named = TRUE, sort = "from")

Arguments

x

input object

named

logical, should vertex names be returned (if they exist) (TRUE) or not (FALSE)

sort

character, name of the column to sort on. Defaults to "from".

Value

data frame

Details

Currently, input can be a matrix, igraph object or network object.

Examples

## from an igraph object
g_i <- igraph::sample_gnp(10, 2/10)
to_edgelist(g_i)
#>   from to
#> 1    1  4
#> 2    2  4
#> 3    2  5
#> 6    2 10
#> 4    3  6
#> 7    3 10
#> 8    4 10
#> 5    5  6
#> 9    9 10

# add vertex names
g1_i <- g_i
igraph::V(g1_i)$name <- LETTERS[seq_len(igraph::gorder(g1_i))]
to_edgelist(g1_i)
#>   from to
#> 1    A  D
#> 2    B  D
#> 3    B  E
#> 6    B  J
#> 4    C  F
#> 7    C  J
#> 8    D  J
#> 5    E  F
#> 9    I  J
# add weights
igraph::E(g1_i)$weight <- seq_len(igraph::ecount(g1_i))
to_edgelist(g1_i)
#>   from to weight
#> 1    A  D      1
#> 2    B  D      2
#> 3    B  E      3
#> 6    B  J      6
#> 4    C  F      4
#> 7    C  J      7
#> 8    D  J      8
#> 5    E  F      5
#> 9    I  J      9
# add further edge attribute
g2_i <- g1_i |> 
    igraph::set_edge_attr("color", value = "red")
to_edgelist(g2_i)
#>   from to weight color
#> 1    A  D      1   red
#> 2    B  D      2   red
#> 3    B  E      3   red
#> 6    B  J      6   red
#> 4    C  F      4   red
#> 7    C  J      7   red
#> 8    D  J      8   red
#> 5    E  F      5   red
#> 9    I  J      9   red

## from a matrix
g_n <- sapply(runif(10, 0, 1), rep, 10)
g_n <- sna::rgraph(10, tprob = g_n)
to_edgelist(g_n)
#>    from to
#> 1     1  7
#> 2     1  9
#> 3     2  7
#> 4     3  2
#> 5     3  9
#> 6     4  2
#> 7     4  9
#> 8     5  2
#> 9     5  4
#> 10    5  9
#> 11    6  2
#> 12    6  3
#> 13    6  4
#> 14    7  3
#> 15    7  4
#> 16    7  9
#> 17    8  2
#> 18    8  3
#> 19    8  7
#> 20    8  9
#> 21    9  2
#> 22    9  7
#> 23    9  8
#> 24    9 10
#> 25   10  1
#> 26   10  2
#> 27   10  9
g_b <- igraph::make_bipartite_graph(c(rep(0, 5), rep(1, 3)), c(1,6,2,7,3,6,3,7,4,8,5,8))
to_edgelist(g_b)
#>   from to
#> 1    1  6
#> 2    2  7
#> 3    3  6
#> 4    3  7
#> 5    4  8
#> 6    5  8

## from a network object
g2_n <- network::as.network.matrix(g_n)
to_edgelist(g2_n)
#>    from to
#> 15    1  7
#> 20    1  9
#> 16    2  7
#> 2     3  2
#> 21    3  9
#> 3     4  2
#> 22    4  9
#> 4     5  2
#> 12    5  4
#> 23    5  9
#> 5     6  2
#> 9     6  3
#> 13    6  4
#> 10    7  3
#> 14    7  4
#> 24    7  9
#> 6     8  2
#> 11    8  3
#> 17    8  7
#> 25    8  9
#> 7     9  2
#> 18    9  7
#> 19    9  8
#> 27    9 10
#> 1    10  1
#> 8    10  2
#> 26   10  9