Add columns to DataFrame

I want to add columns to a dataframe iteratively in a loop and assign them a name. The code below seems to add one column to the dataframe containing value of p at the last iteration and name of the column appears as colname instead of Test10.

Using DataFrames
df = DataFrame()
for i = 1:10
     p = rand(3)
     colname = "Test$i"
     df[!,:colname] = p
end

How to fix this so that the dataframe contains values of p for all iterations (i.e. one column for each iteration) along with column names (e.g. Test1,Test2,…Test10)?

df[!, colname] = p should work (without the : before colname).

3 Likes

Are you coming from Stata, by chance?

:colname is not the same as the variable colname. :colname is an object called a Symbol , which is kind of like a String but not quite.

Thanks!

No, I have not used Stata. Thanks for the clarification

For a constant c, use .= instead of =.

df[!,:colname] .= c