Dear all,

I am trying to generate a loop to create dummy variables for maximum values of a variable (here income) in each group for each year. I have 10 years of data.
Firstly I wish to generate variable max_2018 showing the maximum income in all groups for day == 1 & month == 1 & year == 2018.

bysort group: egen max_2018= max(income) if day == 1 & month == 1 & year == 2018 & id != 0

There will be ties.

For that, the tie breaker is asset_to_debt ratio (variable A2D), which has to be maximum among the ties. So I create a variable maxA2D within each group showing max asset to debt ratio.
So I do:

bysort group: egen maxA2D_2018 = max(A2D) if max_2018 != .

Then I generate a dummy for when maxA2D is equal to A2D (for non-missing values) which generates our dummy for the max income with max A2D within each group.

gen D2018=1 if max_2018 == maxA2D & max_A2D !=.
replace D2018 = 0 if max_A2D == .

Question: These four commands are doing the job for one year i.e. 2018. How to generate a loop that would do this for all 10 years at once?


Thanks in advance!