Search code examples
variableslabelstataencode

Test Based on Label of Encoded Variable


Say I have a string variable, animal, that takes on values dog, cat, and horse. I encode this string variable to get animal2. How can I then test animal2 using the label as opposed to the actual numeric values?

In other words, I can do a logical test on animal as follows:

gen dog = animal=="dog"

But I get an error if I do the same thing with animal2:

gen dog2 = animal2=="dog"

How can I perform this test using the label? Pseudocode is as follows:

gen dog2 = label(animal2)=="dog"

Solution

  • Basic technique here is documented at [U] 13.11 (e.g. here).

    Here is an example:

    . sysuse auto, clear
    (1978 Automobile Data)
    
    . count if foreign=="Domestic":origin
      52
    
    . count if foreign=="Domestic":`: val label foreign'
      52
    

    The last example shows a way of looking up the value label name, which may be useful in programs or do-files.