Assign node attributes in iterative graph making

Viewed 30

I can use the command:

library(igraph)
make_full_graph(10) -> graph

to make a full graph of 10 nodes, and then I can assign node attributes with

graph %>%
  set_vertex_attr(name = "name", value = ...) -> graph

with the next code I can make a union of many graphs into one single graph

do.call(
  graph.disjoint.union,
  lapply(
    1:10,
    make_full_graph
  )
) %>%
  set_vertex_attr(name = "names", value = seq(vcount(.))) %>%
  as_tbl_graph(directed = FALSE)

This would iterate the code for generating a full graph 10 times, then the 10 disjointed graphs would be united. The attribute is assigned to the final united graph, not in the phase of generation of the 10 disjointed.

I want to add attributes generated per each iteration. For example, I want an attribute named iteration that would just indicate with a integer in which iteration of the 10 the node has been generated.

Feel feel to suggest how to improve the generating code with purr.

Reproducible example, with minor differences just to add some randomicity. How would you purr this one?

make_full_graph(sample(1:5)) %>% set_vertex_attr(
  name = "iteration",
  value = 1) -> graph

for (i in c(1:9)){
 graph.disjoint.union(graph,
   make_full_graph(sample(1:5)) %>% set_vertex_attr(
     name = "iteration",
     value = i+1)) -> graph
}
1 Answers

You could use set_vertex_attr within lapply to add the iteration in each loop

do.call(
  graph.disjoint.union,
  lapply(
    1:10,
    function(k) {
      make_full_graph(k) %>% set_vertex_attr(name = "iteration", value = k)
    }
  )
) %>%
  set_vertex_attr(name = "names", value = seq(vcount(.))) %>%
  as_tbl_graph(directed = FALSE)

and you will see

# A tbl_graph: 55 nodes and 165 edges
#
# An undirected simple graph with 10 components
#
# Node Data: 55 x 2 (active)
  iteration names
      <int> <int>
1         1     1
2         2     2
3         2     3
4         3     4
5         3     5
6         3     6
# ... with 49 more rows
#
# Edge Data: 165 x 2
   from    to
  <int> <int>
1     2     3
2     4     5
3     4     6
# ... with 162 more rows
Related