How do I replace these values more efficiently?

Hello,
I am making a dataset in which dtd50 is initially set to zero and I have 6 groups (labeled id).
I want to change dtd50 from zero to six different values (one for each group).
This first block does exactly what I want it to do:

df_pop_Emax = map(i -> DataFrame(id = i, time = 1:1:120, dv_fdiss = missing, dtd50=0), 1:6)
df = vcat(DataFrame.(df_pop_Emax)...)
df[!, :dtd50] = ifelse.(df.id .== 2, -0.5, df.dtd50)
df[!, :dtd50] = ifelse.(df.id .== 3, 0.5, df.dtd50)
df[!, :dtd50] = ifelse.(df.id .== 4, 1, df.dtd50)
df[!, :dtd50] = ifelse.(df.id .== 5, 2, df.dtd50)
df[!, :dtd50] = ifelse.(df.id .== 6, 3, df.dtd50)
df_pop_Emax = df

But it is clunky and requires many shift+enter inputs to get through it. Is there a way to put it all in one chain block? Here is what I tried:

df_Emax = map(i -> DataFrame(id = i, time = 1:1:120, dv_fdiss = missing, dtd50=0), 1:6)
df_vcat_Emax = vcat(df_Emax...)
df_pop_Emax = @chain df_vcat_Emax begin
    _[!,:dtd50] = ifelse.(_.id .== 2, -0.5, _.dtd50)
    _[!,:dtd50] = ifelse.(_.id .== 3, 0.5, _.dtd50)
    _[!,:dtd50] = ifelse.(_.id .== 4, 1, _.dtd50)
    _[!,:dtd50] = ifelse.(_.id .== 5, 2, _.dtd50)
    _[!,:dtd50] = ifelse.(_.id .== 6, 3, _.dtd50)
end

But I cannot get any form of this to run due to errors. Error on this one is “Array has no field id”. I think there is an issue with some outputs being vectors when it needs dataframes.

You can try it a couple of different ways as follows:

# Option 1
df_pop_Emax = @chain df_vcat_Emax begin
    @rtransform :dtd50 = :id == 2 ? -0.5 :
                         :id == 3 ? 0.5 :
                         :id == 4 ? 1 :
                         :id == 5 ? 2 : 
                         :id == 6 ? 3 : 0
end

# Option 2
dtdt50_id_mapping = Dict([1,2,3,4,5,6] .=> [0, -0.5, 0.5, 1, 2, 3])
df_pop_Emax = @rtransform df_vcat_Emax :dtd50 = get(dtdt50_id_mapping, :id, missing)
1 Like

Thank you! That is beautifully simple.