Search code examples
stringlabelstata

How to define a label out of a string variable? (Stata)


I will explain my problem with a simple example: suppose a variable called "var" with the following data: yes, no, may be. Each one as string. I need to do something like this:

foreach i of 0/2{
label define lbl 'i' var['i']
}

(I know there a syntax err, but it's just an example)

The thing is that I want to assign to each numeric value of the label a data from de string variable var and has to start from 0 (already tried with encode command, but haven't been able to change de numeric values using a function like foreach, for, etc). I need to do this because I have a lot of different data inside a variable and can't do it one by one and refuse to believe that I can't do it with stata instead of a text editor. I would really appreciate your help. Thanks!


Solution

  • Perhaps using the encode command with your data will accomplish what you need.

    . list, clean
    
           strvar  
      1.      yes  
      2.       no  
      3.    maybe  
      4.       no  
      5.      yes  
    
    . encode strvar, generate(numvar) label(l_numvar)
    
    . label list l_numvar
    l_numvar:
               1 maybe
               2 no
               3 yes
    
    . list, clean nolabel
    
           strvar   numvar  
      1.      yes        3  
      2.       no        2  
      3.    maybe        1  
      4.       no        2  
      5.      yes        3  
    
    . list, clean
    
           strvar   numvar  
      1.      yes      yes  
      2.       no       no  
      3.    maybe    maybe  
      4.       no       no  
      5.      yes      yes  
    
    .