passing arguments to igraph function within sapply

Viewed 24

I am new to network analyses and ERGM models and have a list of lists which has 100 Erdos Renyi Models as content and was created with the code below

set.seed(666)
gs <- list()
for (x in seq_len(100L)) {
  gs[[x]] <- erdos.renyi.game(374, 0.0084, type = "gnp", directed = F)
  E(gs[[x]])$weight <- sample(1:5, ecount(gs[[x]]), T)
}

Now I would like to calculate the mean path length between two nodes as well as the average clustering across these 100 models. For the mean path length I used the following code:

random_mean_paths <- sapply(gs, igraph::mean_distance, 1:100) 
mean(random_mean_paths)

However, if I try the same with igraph::transitivity , i.e.

random_mean_clus <- sapply(gs, igraph::transitivity, 1:100)

I get the error

Error in match.arg(arg = arg, choices = choices, several.ok = several.ok) : 
  'arg' must be of length 1

and when trying to resolve this error by setting type = "global", i.e.

random_mean_clus <- sapply(gs, igraph::transitivity(type = "global", 1:100)

I get the error argument "graph" is missing with no default

I cannot specify gs in the transitivity() function, since it is not an igraph object and I am stuck trying to pass the correct argument to this function.

Thanks in advance.

1 Answers

Any of

random_mean_clus <- sapply(gs, igraph::transitivity, type = "global", 1:100)
random_mean_clus <- sapply(gs, \(s) igraph::transitivity(s, type = "global", 1:100))

will solve the problem.

The first includes the named argument in the arguments list and the second defines an anonymous function, \(s) using the new way introduced in R 4.1.

Related