Example: creating a graph

In this example we create a graph, assign a random label to the nodes, and sort the edges based on the label of their source node.

The function play_gnp() creates graphs directly through sampling of different attributes.

library(tidygraph)

graph <- tidygraph::play_gnp(n = 10, p = 0.2) %>% 
  activate(nodes) %>% 
  mutate(class = sample(letters[1:4], n(), replace = TRUE)) %>% 
  activate(edges) %>% 
  arrange(.N()$class[from])

graph
## # A tbl_graph: 10 nodes and 19 edges
## #
## # A directed simple graph with 1 component
## #
## # Edge Data: 19 × 2 (active)
##     from    to
##    <int> <int>
##  1     5     1
##  2     1     2
##  3     5     3
##  4     5     8
##  5     7     8
##  6     6     1
##  7     3     2
##  8     6     2
##  9     6     5
## 10    10     8
## 11    10     9
## 12     2     3
## 13     2     6
## 14     9     6
## 15     4     2
## 16     8     2
## 17     8     5
## 18     8     7
## 19     8    10
## #
## # Node Data: 10 × 1
##   class
##   <chr>
## 1 a    
## 2 c    
## 3 b    
## # ℹ 7 more rows

Conversion to tbl_graph

Convert data with as_tbl_graph(). A tbl_graph is a data structure for tidy graph manipulation. It converts a data frame encoded as an edgelist.

data(highschool, package = "ggraph")
head(highschool)
##   from to year
## 1    1 14 1957
## 2    1 15 1957
## 3    1 21 1957
## 4    1 54 1957
## 5    1 55 1957
## 6    2 21 1957

With as_tbl_graph() we get:

hs_graph <- tidygraph::as_tbl_graph(highschool, directed = FALSE)
hs_graph
## # A tbl_graph: 70 nodes and 506 edges
## #
## # An undirected multigraph with 1 component
## #
## # Node Data: 70 × 0 (active)
## #
## # Edge Data: 506 × 3
##    from    to  year
##   <int> <int> <dbl>
## 1     1    13  1957
## 2     1    14  1957
## 3     1    20  1957
## # ℹ 503 more rows