Issues with For Loop - Appending New DataFrames

Hello! I’m trying to run a pretty simple for loop. The premise is that I have a dataframe with 250 different subjects with time points over a number of different dates/times. The issue is that I need my my time to be sequential - but as it stands, with each new day starts a new time = 0. To solve this, I want to mark the turn of each new day for each subject, and add in sequential times accordingly. I’m having issue with the initial for loop in which I keep getting an error that df_fin does not exist. Any help would be appreciated!

create a column that marks each change of DATE for each ID

df_pk.OCC_DATE = 1
df_fin = DataFrame()
for i = 1:250
df_new = df_pk |> @filter(_.ID == i)
df_new = DataFrame(df_new)
for n = 2:length(df_new.ID)
if df_new.DATE[n] != df_new.DATE[n-1]
df_new.OCC_DATE[n] = df_new.OCC_DATE[n-1]+1
df_new.OCC_DATE[n] = df_new.OCC_DATE[n-1]
df_fin = vcat(df_fin, df_new)

create a new time based on OCC_DATE

for i = 1:length(df_fin.ID)
if OCC_DATE == 1
df_pk.TIME_NEW[i] = df_pk.TIME[i]
elseif OCC_DATE == 2
df_pk.TIME_NEW[i] = df_pk.TIME[i]+24
elseif OCC_DATE == 3
df_pk.TIME_NEW[i] = df_pk.TIME[i]+48
elseif OCC_DATE == 4
df_pk.TIME_NEW[i] - df_pk.TIME[i]+72

Take a look at some tips for how to post code on discourse.

I think you are running to the sometimes unintuitive behavior of global scope.

Try adding global df_fin right after your for i = 1:250.

1 Like