Skip to content
Prev 387754 / 398502 Next

Assigning several lists to variables whose names are contained in other variables

Hello,

I believe that the point we are missing is that datatable$column stores 
the *names* of the graphs, not the graph objects themselves. So in the 
loop the objects must be retrieved with mget() or get().

First create a reproducible example.



library(tidygraph)

my_function <- function(g){
   stopifnot(inherits(g, "igraph"))
   g %>% mutate(centrality = centrality_pagerank())
}

MYSUBNET1 <- create_notable('bull')
iris_clust <- hclust(dist(iris[1:4]))
MYSUBNET2 <- as_tbl_graph(iris_clust)
MYSUBNET3 <- play_smallworld(1, 100, 3, 0.05)

datatable <- data.frame(column = paste0("MYSUBNET", 1:3))



Now apply the function above to each of the "tbl_graph" objects.

1. Get all objects and apply the function in one instruction. Then 
assign the new names.


result <- lapply(mget(datatable$column, envir = .GlobalEnv), my_function)
names(result) <- paste("subnet", datatable$column, sep = "_")


2. Loop through the column with lapply, getting one object and applying 
the function one at a time. Then assign the new names.



result2 <- lapply(datatable$column, function(net_name){
   NET <- get(net_name, envir = .GlobalEnv)
   my_function(NET)
})
names(result2) <- paste("subnet", datatable$column, sep = "_")



3. Loop through the column with a for loop, getting one object and 
applying the function one at a time. Then assign the new names.



result3 <- vector("list", length = nrow(datatable))
for(i in seq_along(datatable$column)){
   net_name <- datatable$column[i]
   NET <- get(net_name, envir = .GlobalEnv)
   result3[[i]] <- my_function(NET)
}
names(result3) <- paste("subnet", datatable$column, sep = "_")



4. Now check that all 3 solutions give the same result.


identical(result, result2)
#[1] TRUE
identical(result, result3)
#[1] TRUE


Is this it?

Rui Barradas


?s 17:23 de 09/04/21, Wolfgang Grond escreveu: