Loop over the variable name inside of function

Hi, I want to make a simple function with colnames x1, x2, …

So I made a below function and realized that “df” should be outside of the function.

Why the loop does not work if “df” is inside of the function?

I want to make a function including df inside.

Could someone help me?

Happy new year!

> function ASD(k::Int64)
>     df=DataFrame()
>     for i in 1:k
>          @eval df.$(Symbol("x$i")) = randn(10)
>     end
> 
>     return df
> end
a=ASD(2)
1 Like

Welcome to the forum. I suggest you not using eval for nothing similar to that, it is not needed. You can use df[¡, name] to create a new column.
You can directly use :auto.

df= DataFrame(rand(n, k), :auto)

I suggest to read the wonderful documentation.
Happy new year!

As to why, @eval works in the global scope. Routine advice is not to use @eval.