How to replace arbitrary values of a variable with sequential values?

Viewed 18

<For example: a variable has values 1 2 3 5 10 11 12 13 14 20 21 .... I want to replace it with 1 2 3 4 5 6 7 8 9 10 11..... I was using this command but is not giving, the desired results: old variable=district I want to replace value with the correct sequential values>

levelsof district, local(district_new)
foreach i in `district_new'{
    replace district= mod(_n-1,707)+1
}
2 Answers

Not fully sure what you trying to do, but is this a solution to what you are trying to do:

sort district
replace district = _n

This will replace the values in district with 1 for the lowest current value, 2 for the second lowest value etc. This might not be a good solution if your variable may have duplicates.

I agree with @TheIceBear but more can be said that won't fit easily into comments.

The particular code posted boils down to a single statement repeated

replace district = mod(_n-1,707) + 1

as that action is repeated regardless of the values of district. In a dataset with 707 or fewer observations, that in turn would be equivalent to

replace district = _n 

as @TheIceBear points out. If there were duplicate observations on any district, this would definitely be a bad idea, and something like

egen newid = group(district), label 

would be a better idea. For more, see https://www.stata.com/support/faqs/data-management/creating-group-identifiers/

Related