Hi,

I am having some trouble with my coding for STATA currently. I have panel data that has multiple observations for each individual (sometimes 2, sometimes more) and another variable in the dataset that codes as a 1 or 0 if the individual was positive for this variable (called A). I am trying to create a couple more variables, one that is a 1 for the individual if they were A==1 at their first observation (so time ==1) and 0 if not and then another variable that is a 1 for the individual if they were A==1 at their last observation in the data set (which for some individuals is at time==2 and for some it is time ==11).

This is the coding I have tried so far with A1first being the new variable if the individual was A=1 at their first observation:
by id (time), sort: egen A1first = min(cond(A==1, time, 0))
replace A1first = 1 if A1first!=0

For the most part this works, but if the individual was A=1 on their first observation and A=0 on their last then STATA seems to be coding that individual as A1first=0 rather than A1first=1 which is what I would like it to do. I having the same problem when I attempt to create the variable A1last:

by id (time), sort: egen A1last = max(cond(A==1, time, 0))
replace A1last = 1 if A1last!=0

This works unless that individual was A=1 on their first observation but not their last, then it codes the individual in this case as Alast =1 rather than Alast=0.

Any help would be greatly appreciated.