naivaidya garg
naivaidya garg

Reputation: 11

creating a new empty data frame in each loop?

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'.

Upvotes: 1

Views: 37

Answers (1)

Martin Gal
Martin Gal

Reputation: 16988

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]]

Upvotes: 4

Related Questions