0

I have around 500 dataframes with two columns and a varying number of rows (from 10 till 30) in R. I also have a character vector containing the names for the dataframes. I now wish to bundle all these dataframes into a single list so I can refer to these list elements using the dataframe names. I was thinking to use a loop to loop through the dataframes and add them to the list in each step but I couldn't pull it of.

WBM
  • 129
  • 4
  • 2
    Can you share a minimal reproducible example? – markus Feb 13 '19 at 13:34
  • 4
    `mget()`, however, you should not create 500 separate data.frames to begin with. Put them into a list when they are created. – Roland Feb 13 '19 at 13:48
  • 1
    https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames Gregor's answer in this question is a good read. – RLave Feb 13 '19 at 14:17

2 Answers2

5

The following works:

df_list = mget(df_names)

However, the real solution is to not have 500 data.frames in your workspace to begin with: either load/create them immediately inside a list, or have your data in such a format that it’s collated into one big data.frame.

Think of variables as things you have to keep in your head at the same time: if there are too many to remember, you have too many. Because how else can you reason about the state of your program, i.e. about its semantics and correctness?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
0

Check this:

df_names <- c(    ) # yours dataframes names character vector
lst <- list()

for (i in df_names) {
  lst[i] <- list(get(i))
}
Paweł Chabros
  • 2,349
  • 1
  • 9
  • 12