Search code examples
stata

Retrieve row number according to value of another variable in index


This problem is very simple in R, but I can't seem to get it to work in Stata.

I want to use the square brackets index, but with an expression in it that involves another variable, i.e. for a variable with unique values cumul I want:

replace country = country[cumul==20] in 12

cumul == 20 corresponds to row number 638 in the dataset, so the above should replace in line 12 the country variable with the value of that same variable in line 638. The above expression is clearly not the right way to do it: it just replaces the country variable in line 12 with a missing value.


Solution

  • Stata's row indexing does not work in that way. What you can do, however, is a simple two-line solution:

        levelsof country if cumul==20
        replace  country = "`r(levels)'" in 12
    

    If you want to be sure that cumul==20 uniquely identifies just a single value of country, add:

        assert `:word count `r(levels)''==1
    

    between the two lines.