0

I've tried searching for the answer to this but am having trouble because I'm not sure I'm even searching the right thing. Basically I would like in R to create a loop to create multiple objects, each from a different object. For example, let's say I have 50 existing objects (matrix, data frame, graph etc.) and they are all named similarly (table1, table2...table50). Now I would like to create 50 new objects, lets say graph1...graph50. I'm having trouble with a loop because I don't know how to work with the names being strings. I've tried the assign function, but it isn't dynamic enough in the assignment argument. I would basically like something like this:

for (i in list(table names)){ graph "i" <- as.network(table "i") }

I would also like to have this hold for objects assigned as some function of itself ie graph "i" <- somefunction(graph "i") etc...

Additionally if there is a more efficient way by all means I'm open to it. It seems like an easy task but I can't figure it out. Right now I'm literally just concatenating the statements in excel and pasting to R so it doesn't take too long, but it is a pain. Thank you.

Ron Ransom
  • 73
  • 1
  • 6
  • 3
    [Use lists](https://stackoverflow.com/a/24376207/903061). – Gregor Thomas Mar 15 '19 at 19:49
  • 1
    How did you create all these objects in the first place? It's much better when creating related objects to create them in a list. It's a bad idea to have a bunch of variables in your global environment that different with just a numeric suffix. Once you have data in a list, then you can map any function you like over that list easily. – MrFlick Mar 15 '19 at 19:50
  • 3
    If you already had a list of tables called `list_of_tables`, then you would create the list of graphs with `list_of_graphs = lapply(list_of_tables, as.network)`. Other things would work similarly. – Gregor Thomas Mar 15 '19 at 19:51
  • Yes thank you so much. I apparently just didn't know how to use lists properly but it's all super easy and much cleaner now thank you. – Ron Ransom Mar 15 '19 at 20:07

1 Answers1

-1

I think you could have a nested loop to do what you're looking for; you could could apply whatever transformations you're wanting to each object within the input list and store the results in a new list with the same object names.

in_list <- list(table1 = iris, 
                table2 = EuStockMarkets)
out_list <- list()

for(i in 1:length(in_list)){
  for(j in colnames(in_list[[i]])){
    out_list[[ gsub("table", "graph", names(in_list)[i]) ]][[j]] <- summary(in_list[[i]][,j])
  }
}

Hope this helps!

Doober
  • 1