How do I add a new column to a dataframe in Julia using conditional logic?

I want to create a new column in my dataframe. If another column equals zero, I want this column to equal zero. If it doesn’t, I would like this column to equal another column divided by a third column. I tried using the @rtransform dataframes meta macro but keep getting various errors. Is there a generally accepted way to do this?

@rtransform df :z = :y == 0 ? 0 : :z
1 Like

It’s true that it might be nice for a more convenient @replace command because there is no way to do this without repeating the variable name more frequently than is ideal.

Base Julia:

julia> df = DataFrame(a = Int.(rand(Bool, 10)), b = 1:10, c = 10:-1:1)

julia> df.d = @. ifelse(df.a == 0, 0.0, df.b / df.c); df
10Γ—4 DataFrame
 Row β”‚ a      b      c      d        
     β”‚ Int64  Int64  Int64  Float64  
─────┼───────────────────────────────
   1 β”‚     0      1     10   0.0
   2 β”‚     0      2      9   0.0
   3 β”‚     1      3      8   0.375
   4 β”‚     0      4      7   0.0
   5 β”‚     0      5      6   0.0
   6 β”‚     0      6      5   0.0
   7 β”‚     1      7      4   1.75
   8 β”‚     1      8      3   2.66667
   9 β”‚     1      9      2   4.5
  10 β”‚     1     10      1  10.0
2 Likes

You could calculate/construct the new column, by putting into formula the conditions you have illustrated

df.d.=(df.b./df.c).*(df.a.!=0)
#or 
@. df.d=(df.b/df.c)*(df.a!=0)

2 Likes

This worked perfectly. Thank you @pdeffebach !