How to save results for each outcome?

Sorry my fault for writing pseudocode - the DataFrame indexing in the loop returns a one-element array on the left hand side, so assignment needs to be broadcasted.

Here’s a full MWE (note the .= in the loop):

julia> using CSV, DataFrames, GLM

julia> data = DataFrame(x1 = rand(500), x2 = rand(500));

julia> data[!, :A] = 5 .+ 0.5*data.x1 - 1.5*data.x2 .+ randn.();

julia> data[!, :B] = 1 .+ 2.5*data.x1 + 3.5*data.x2 .+ randn.();

julia> list = [:A, :B];

julia> results = DataFrame("y" => list, (["x1", "x2"] .=>  [Vector{Float64}(undef, length(list)) for _ ∈ 1:2])...);

julia> for depvar ∈ list
           ols_result = lm(term(depvar) ~ term(:x1) + term(:x2), data)
           results[results.y .== depvar, :x1] .= coef(ols_result)[1]
           results[results.y .== depvar, :x2] .= coef(ols_result)[2]
       end

julia> results
2×3 DataFrame
 Row │ y       x1        x2       
     │ Symbol  Float64   Float64  
─────┼────────────────────────────
   1 │ A       5.17577   0.495342
   2 │ B       0.975703  2.6233
1 Like