0

I am new to R.

I am trying to create a loop where I create multiple networks at the same time. Something like:

#loading required packages 
library(igraph)
library(tidygraph)

for (i in 1:10) {
G[i]=play_erdos_renyi(10, .2)
}

Where i-th element of G will store the graph generated from the i-th draw. Any idea what kind of of object I need G to be defined as?

AC24
  • 5
  • 2
  • 1
    `G` should be a `list()` object. If you are just trying to replicate that command 10 times, you can go `G <- replicate(10, play_erdos_renyi(10, .2), simplify = FALSE)` and that will create the list for you. You extract elements with `G[[1]]` rather than `G[1]` – MrFlick Aug 16 '21 at 03:10
  • But this doesn't recognize the elements of G to be graph objects, so that I can e.g. manipulate G[[5]] later on as a graph. Is there any way to do that? – AC24 Aug 16 '21 at 16:59
  • What does that mean exactly? What manipulations are you unable to do? There shouldn't be any difference between the value from the list and calling the function directly for most use cases. If you have a new problem, perhaps you should open a new question. – MrFlick Aug 16 '21 at 17:01
  • No, I mean for example I want to do: V(G[[1]])$attribute=sample(c(0,1), size =vcount(G[[1]), replace = T). Basically, treating an element of G as a graph object. Can that be done? – AC24 Aug 16 '21 at 17:03
  • Well, in this case `G` only goes to 10 so there is no `G[[14]]` If I run `V(G[[4]])$trueprob = sample(c(0,1), size =vcount(G[[4]]), replace = T)` it seems to work just fine. I can look at `V(G[[4]])$trueprob` after the fact and see the values have been set. – MrFlick Aug 16 '21 at 17:07

1 Answers1

0

As @MrFlick suggests, you should store the multiple network objects in a list(), and you can use the following to create the list if you simply need to replicate the same network 10 times:

G = replicate(10, play_erdos_renyi(10, .2), simplify = FALSE)

If your network constructor is dependent on your value of i, then I would recommend using a map function from the purrr package which is guaranteed to return a list, for example:

G = map(1:10, ~play_erdos_renyi(.x, 10, .2))

Ayush Noori
  • 176
  • 5