Adding a column to a dataframe and conditionally filling based on another column within the same dataframe

I’m trying to write code to do the following, I’m completely new to Julia and coding in general so really struggling.
I have a data frame of columns and rows, I need to add a new column (EVID) to the df and conditionally fill based on the values in a different column (AMT). The conditional rule is “if AMT is missing then EVID is equal to 0. If AMT is not missing then EVID is equal to 1”

I think what I’m stumbling on is doing two things at once, i.e. inserting a new column (EVID) and then conditionally filling it based on the contents of a different column.

Here’s a solution with DataFramesMeta.jl

julia> using DataFramesMeta, DataFrames

julia> df = DataFrame(AMT = [1, 4, 3, missing, 3, 2])
6×1 DataFrame
 Row │ AMT     
     │ Int64?  
─────┼─────────
   1 │       1
   2 │       4
   3 │       3
   4 │ missing 
   5 │       3
   6 │       2

julia> @rtransform df :EVID = ismissing(:AMT) ? 0 : 1
6×2 DataFrame
 Row │ AMT      EVID  
     │ Int64?   Int64 
─────┼────────────────
   1 │       1      1
   2 │       4      1
   3 │       3      1
   4 │ missing      0
   5 │       3      1
   6 │       2      1
1 Like

Thank you.

TidierData.jl is another option that would look like this

julia> using TidierData

julia> df = DataFrame(AMT = [1, 4, 3, missing, 3, 2])
6×1 DataFrame
 Row │ AMT     
     │ Int64?  
─────┼─────────
   1 │       1
   2 │       4
   3 │       3
   4 │ missing 
   5 │       3
   6 │       2

julia> @mutate(df, EVID = if_else(ismissing(AMT), 0, 1))
6×2 DataFrame
 Row │ AMT      EVID  
     │ Int64?   Int64 
─────┼────────────────
   1 │       1      1
   2 │       4      1
   3 │       3      1
   4 │ missing      0
   5 │       3      1
   6 │       2      1
2 Likes

Or just broadcast ifelse.()

using DataFrames
df = DataFrame(AMT = [1, 4, 3, missing, 3, 2])
df.EVID = ifelse.(ismissing.(df.AMT), 0, 1)
6×2 DataFrame
 Row │ AMT      EVID  
     │ Int64?   Int64 
─────┼────────────────
   1 │       1      1
   2 │       4      1
   3 │       3      1
   4 │ missing      0
   5 │       3      1
   6 │       2      1
1 Like