I would say that this question is posed incorrectly for a better understanding. The goal is to group observations, those with the lowest value, which are assigned class 1, and the next lower one - to all assigned 2, and so on. This does not apply to most of the feelings that I have already mentioned, but Stata egen, rank() makes you part of this journey.
But the direct path mentioned in the Statalist topic mentioned above is simpler in spirit than any solution cited:
bysort group_id (var_to_rank): gen desired_rank = sum(var_to_rank != var_to_rank[_n-1])
As soon as the data is sorted by var_to_rank , then when the values ββdiffer from the previous values ββat the beginning of each block of different values, the value 1 is the result of var_to_rank != var_to_rank[_n-1] ; otherwise 0 is the result. Summing these 1s and 0s cumulatively gives the desired variable. The prefix bysort does the sorting and ensures that all this is done separately in the groups defined by group_id . There is no need for egen at all (a command that many people who use Stata often find strange).
Declaration of Interest: The quoted quote from Statalist shows that when I asked a similar question, I also did not think about this solution in one.
source share