Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Loop through value label

    Hi Stata users,

    I would like to generate a new variable based on the contents of a value label. Below is an example am trying to come up with so that I can replicate in my dataset

    Code:
        sysuse auto, clear
    
        gen dum = .
        levelsof foreign, local(levels)
        foreach l of local levels {
            di "`: label (foreign) `l''"
            replace dum = 0 if inlist("`: label (foreign) `l''", "Domestic")
            replace dum = 1 if inlist("`: label (foreign) `l''", "Foreign")
         }
    The idea is to create a new variable if a string is part of a value label.

    Thanks in advance!

  • #2
    I'd decode and then test for a string.

    Comment


    • #3
      Thanks Nick Cox for the idea. I am wondering whether the alternative is computationally efficient for someone working with about 100 files of population surveys one of the countries being India

      Comment


      • #4
        If you want to match the exact text in the value label, something like

        Code:
        generate byte indicator = foreign == "Domestic":origin
        is possible. Otherwise, Nick's advice is probably the best approach.

        Comment


        • #5
          Thanks so much daniel klein for your proposed approach. Actually I finally found a solution in line with my original code that I'll share in the next post

          Comment


          • #6
            First, I would like to apologize since the example I used may not be capable of representing the complex challenge I was addressing. The aim is to standardize response on level of education for different countries that may be in English or French. That's why
            Code:
            inlist
            would come in handy. However, the example still forms a foundation to achieving my desired goal.
            Below is a code with my desired

            Code:
                sysuse auto, clear
                
                gen dum = .
                levelsof foreign, local(levels)
                foreach l of local levels {
                    di "`: label (foreign) `l''"
                    
                    replace dum = 0 if foreign == `l' & inlist("`: label (foreign) `l''", "Domestic")
                    replace dum = 1 if foreign == `l' & inlist("`: label (foreign) `l''", "Foreign")
                 }
                 
                 ta foreign dum
            Thanks all who have taken their precious time to assist me. I sincerely appreciate.

            Comment

            Working...
            X