1

I'm trying to create a new data frame for each one of my loops in a for loop; but i can't seem to get a new data frame each time.

for(j in 1:10){
    df_j = data.frame()
}

What I am trying to get is a bunch of new data frames in my environment.

df_1 df_2 df_3 df_4 df_5 df_6 df_7 df_8 df_9 df_10

Im quite new to coding, so any help will be appreciated, thanks.

When i tryied this it just made one data frame called 'df_j'.

Martin Gal
  • 16,640
  • 5
  • 21
  • 39

1 Answers1

4

Creating new variables in a loop / automatically isn't a good idea. Consider using a list instead:

  • Outside the for loop create my_list <- list().
  • Inside your loop assign the new data.frames using my_list[[j]] <- data.frame().
  • Access a data.frame for example via my_list[[5]] which is more or less your intended df_5.
my_list <- list()

for(j in 1:10){
  my_list[[j]] <- data.frame()
}

my_list[[5]]
Martin Gal
  • 16,640
  • 5
  • 21
  • 39
  • 2
    Also see @GregorThomas’s [classic answer](https://stackoverflow.com/a/24376207/17303805) on why a list of dataframes is usually preferable to a bunch of dataframes loose in the environment. – zephryl Dec 04 '22 at 15:17