Suppose I have a DataFrame like this
df = DataFrame("a" => [1,2], "b" => [3,4])
2×2 DataFrame
Row │ a b
│ Int64 Int64
─────┼──────────────
1 │ 1 3
2 │ 2 4
and I want to calculate several new columns using the function
function my_weird_fun(x,y)
return x+y, x-y, x*y, x/y
end
I can do this
transform(data, [:a,:b] => ByRow(my_weird_fun) => [:plus,:minus,:times,:div])
2×6 DataFrame
Row │ a b plus minus times div
│ Int64 Int64 Int64 Int64 Int64 Float64
─────┼─────────────────────────────────────────────
1 │ 1 3 4 -2 3 0.333333
2 │ 2 4 6 -2 8 0.5
But what if I only want to use the first row of a
and b
and broadcast the result to all rows of the new columns, so that the result is
2×6 DataFrame
Row │ a b plus minus times div
│ Int64 Int64 Int64 Int64 Int64 Float64
─────┼─────────────────────────────────────────────
1 │ 1 3 4 -2 3 0.333333
2 │ 2 4 4 -2 3 0.333333
Is there a way to achieve this using transform
?
EDIT: This works but feels rather hacky:
transform(df, :a => ByRow(x->my_weird_fun(df.a[1],df.b[1])) => [:plus,:minus,:times,:div])
Is there a way I can achieve this without direct reference to df
which might come out of a @chain
?