Announcement

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

  • How to store values of a variable in a local macro

    Dear Statalist,

    I am running Stata 12.1 on Windows 7, Home Premium,

    I have a str3 variable "country" which has three unique values (many observations): ABC, DEF, GHI.

    I want to store the three string values ABC, DEF and GHI in a local macro "countrylist" for further use. Right now I am entering them into the local macro manually, but later I may add more data to my current dataset and then the string variable "country" will have more unique values than just three. I do not want to rewrite the do file again. Is there some way to automatically enter the unique values of the variable "country" into the local macro "countrylist"?

    Right now my code looks like the following

    Code:
    input str3 country var1 var2
    ABC    5    7
    DEF 6    8
    GHI 2    3
    ABC    1    8
    DEF 0    9
    GHI 1    4
    ABC    4    5
    DEF 3    3
    GHI 5    2
    end
    
    local countrylist ABC DEF GHI
    
    foreach country of local countrylist{
                     reg var1 var2 if country == "`country'"
                     predict var1_hat if country == "`country'"
    }

    Thank you.

  • #2
    This is what levelsof does.

    For "unique" read "distinct".

    Nevertheless, see http://www.stata.com/support/faqs/da...ach/index.html for other approaches.

    Comment


    • #3
      Thank you Dr. Cox.

      Comment


      • #4
        Notice also that your loop would fail second time around as then var1_hat already exists.

        Code:
        gen var1_hat = .  
        foreach country of local countrylist {
             reg var1 var2 if country == "`country'"    
             predict work if country == "`country'"    
             replace var1_hat = work if country == "`country'"      
             drop work  
        }
        Last edited by Nick Cox; 07 Apr 2015, 12:00.

        Comment


        • #5
          Yes it did, then I corrected that line in my do file.

          Comment

          Working...
          X