I'm trying to learn metaprogramming. Using some data I loaded into a 
DataFrame, I'd like to generate some variables so I can access them without 
going through the DataFrame. Additionally, I might want to generate some 
interaction terms. For example, if I had a variable 'X" and a variable 'Y', 
I could generate a variable 'XY' defined as their product.

I found some example code in an earlier post ( 
https://groups.google.com/forum/#!searchin/julia-users/declare$20variables$20metaprogramming/julia-users/hBQp_RuKV5c/DHDGLGXJODQJ
 
) that seemed like it should help, but it doesn't work when I apply it to 
my DataFrame. Here's my code.

using DataFrames
df = convert(DataFrame,rand(2,2))
names!(df,[:I,:B])
@eval $:I = 2
@eval $names(df)[1] = 2

Everything works except the last line. I find this quite odd. names(df)[1] 
is exactly the Symbol " :I ". As far as I can tell, the expressions I am 
trying to evaluate are identical, yet the first one works and the second 
one doesn't. It returns the error 

`convert` has no method matching convert(::Type{Symbol}, ::Int64)
while loading In[13], in expression starting on line 1

 in setindex! at array.jl:307


But, I've found that if I put the same thing inside of a for loop, it 
works. That is,

for i in names(df)
    eval(:($i = 4))
    #eval( :($i = df[i] ))
end

works, and creates variables 'I' and 'B' with the value 4. The line I've 
commented out is supposed to do what I actually want and assign the data 
values to the variables. But it doesn't work. I've tried adding an extra $, 
for example, $df[i] or df[$i], but that doesn't work either. 

To summarize, my questions are:
1. What messed up my first example when I replaced the explicit code with 
an (identical?) Symbol.
2. Why did using a for loop fix that?
3. What do I have to do in the for loop to assign the data to the 
corresponding variable?

I'm pretty new to Julia, so any help would be much appreciated. Thanks!

Reply via email to