Announcement

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

  • Create a set of dummies and rename them

    Dear All,

    consider the following dataset:

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float(invest market stock) str5 company byte time float id
    317.6 3078.5   2.8 "Firm1" 1 1
    391.8 4661.7  52.6 "Firm1" 2 1
    410.6 5387.1 156.9 "Firm1" 3 1
    257.7 2792.2 209.2 "Firm1" 4 1
    330.8 4313.2 203.4 "Firm1" 5 1
    40.29  417.5  10.5 "Firm2" 1 2
    72.76  837.8  10.2 "Firm2" 2 2
    66.26  883.9  34.7 "Firm2" 3 2
     51.6  437.9  51.8 "Firm2" 4 2
    52.41  679.7  64.3 "Firm2" 5 2
     33.1 1170.6  97.8 "Firm3" 1 3
       45 2015.8 104.4 "Firm3" 2 3
     77.2 2803.3   118 "Firm3" 3 3
     44.6 2039.7 156.2 "Firm3" 4 3
     48.1 2256.2 172.6 "Firm3" 5 3
    12.93  191.5   1.8 "Firm4" 1 4
     25.9    516    .8 "Firm4" 2 4
    35.05    729   7.4 "Firm4" 3 4
    22.89  560.4  18.1 "Firm4" 4 4
    18.84  519.9  23.5 "Firm4" 5 4
    209.9 1362.4  53.8 "Firm5" 1 5
    355.3 1807.1  50.5 "Firm5" 2 5
    469.9 2676.3 118.1 "Firm5" 3 5
    262.3 1801.9 260.2 "Firm5" 4 5
    230.4 1957.3 312.7 "Firm5" 5 5
    end

    I would like to generate a set of dummies, one for each group under the variable id, Hence I type:

    Code:
    tab id, gen(c)
    Then, I would like to rename each dummy with the corresponding name under the variable company. So dummy c1 should be Firm1, dummy c2 should be Firm2 and so on.

    I have seen the following post:

    https://www.statalist.org/forums/for...s-using-a-loop

    The point is that my original dataset contains more than 150 groups and it is quite long to write down 150 names if I would like to use something like:

    Code:
    rename (c1-c5) (Firm1 Firm2 ....)
    I would like to know if there is a quicker way to do so. Myabe using a loop? I have thought to use levelsof but I cannot figure out how to set a loop to assign the correct name to each dummy.

    Thanks in advace for your kind help.

  • #2
    You need to ensure that the strings are valid Stata names. You can do something like:

    Code:
    gen id2= strtoname(company)
    levelsof id2, local(ids)
    foreach id in `ids'{
        gen `id'= id2=="`id'"
    }

    Comment


    • #3
      Andrew Musau Thanks a lot. It worked fine.

      Comment

      Working...
      X