1

I am trying to generate n dataframes using a loop, where each dataframe has one column with i rows populated with random numbers where i=1:n. So far, none of the following iterating methods work for iterating over dataframe names in order to generate them:

n = 5;
for i = 1:n 
    "df_$i" = DataFrame(rand($i), :auto)
end

or

n = 5;
for i = 1:n 
    "df_$(i)" = DataFrame(rand($i), :auto)
end

Thanks!

Moshi
  • 193
  • 6
  • 1
    Perhaps a `Vector{DataFrame}` would be better? Most likely you would like to manipulate these dataframes together later and the loop code would be easier. – Dan Getz Oct 25 '22 at 18:36
  • Thanks Dan for your answer. This has also been suggested by Bogumil. i will try and see if this can be applied in my actual problem. – Moshi Oct 26 '22 at 23:03

1 Answers1

2

Is this what you want?

julia> [DataFrame("col$i" => rand(i)) for i in 1:3]
3-element Vector{DataFrame}:
 1×1 DataFrame
 Row │ col1
     │ Float64
─────┼──────────
   1 │ 0.368821
 2×1 DataFrame
 Row │ col2
     │ Float64
─────┼──────────
   1 │ 0.757023
   2 │ 0.201711
 3×1 DataFrame
 Row │ col3
     │ Float64
─────┼──────────
   1 │ 0.702651
   2 │ 0.256179
   3 │ 0.560374

(I additionally showed you how to dynamically generate the name of the column in each data frame)

Bogumił Kamiński
  • 66,844
  • 3
  • 80
  • 107
  • Thanks Bogumil for your answer. I will try to see if you answer which involves generating a Vector{DataFrame} (as was also suggested by Dan) works in my case. What I am eventually trying to do is quite complex, but is hindered as of now with the inability to loop over dataframe names. I have a function which "cleans" and "generates" a new dataframe. In doing so, I need to create/work with multiple intermediate dataframes for `j` time periods (t) and `n` groups (g) -- for which i want to loop over t and g to create df_t1_g1 ... df_tj_g1, ..., df_t1_gn, ... df_tj_gn and then work with them. – Moshi Oct 26 '22 at 23:03
  • you can use a `Dict` mapping names as keys to data frames as values instead. – Bogumił Kamiński Oct 27 '22 at 05:48