The iterate family of functions allow you to call the same modification function on a graph until some condition is met. This can be used to create simple simulations in a tidygraph friendly API
iterate_n(.data, n, .f, ...)
iterate_while(.data, cnd, .f, ..., max_n = NULL)
A tbl_graph
object
The number of times to iterate
A function taking in a tbl_graph
as the first argument and
returning a tbl_graph
object
Further arguments passed on to .f
A condition that must evaluate to TRUE
or FALSE
determining if
iteration should continue
The maximum number of iterations in case cnd
never evaluates
to FALSE
A tbl_graph
object
# Gradually remove edges from the least connected nodes while avoiding
# isolates
create_notable('zachary') |>
iterate_n(20, function(gr) {
gr |>
activate(nodes) |>
mutate(deg = centrality_degree(), rank = order(deg)) |>
activate(edges) |>
slice(
-which(edge_is_incident(.N()$rank == sum(.N()$deg == 1) + 1))[1]
)
})
#> # A tbl_graph: 34 nodes and 58 edges
#> #
#> # An undirected simple graph with 1 component
#> #
#> # Node Data: 34 × 2 (active)
#> deg rank
#> <dbl> <int>
#> 1 14 10
#> 2 4 12
#> 3 7 17
#> 4 5 18
#> 5 3 21
#> 6 3 24
#> 7 4 25
#> 8 3 26
#> 9 4 27
#> 10 1 28
#> # ℹ 24 more rows
#> #
#> # Edge Data: 58 × 2
#> from to
#> <int> <int>
#> 1 1 3
#> 2 1 4
#> 3 1 5
#> # ℹ 55 more rows
# Remove a random edge until the graph is split in two
create_notable('zachary') |>
iterate_while(graph_component_count() == 1, function(gr) {
gr |>
activate(edges) |>
slice(-sample(graph_size(), 1))
})
#> # A tbl_graph: 34 nodes and 51 edges
#> #
#> # An undirected simple graph with 2 components
#> #
#> # Node Data: 34 × 0 (active)
#> #
#> # Edge Data: 51 × 2
#> from to
#> <int> <int>
#> 1 1 2
#> 2 1 5
#> 3 1 6
#> # ℹ 48 more rows