Announcement

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

  • How to rename variable name with the variable label in a loop

    I created new variables based on the levels of a categorical variable using the -tab, gen- command and want to reproducibly label the new variables based on the value label of the category. Example below:

    Code:
    webuse auto, clear
    tab make, gen(mak)
    des mak*
    The new variables mak1, mak2, mak3, etc have the variable label as make==AMC Concord, make==AMC Pacer, make==AMC Spirit, respectively, etc. My question is how do I remove the 'make==' prefix of the variable label and use the actual label 'AMC Concord', AMC Pacer, AMC Spirit', etc to rename the new variables mak1, mak2, mak3 etc, reproducibly, possibly by using loops?

    If this is possible, any help here will be appreciated.

    Thanks,

    Madu

  • #2
    Perhaps this?
    Code:
    sysuse auto, clear
    tab make, gen(mak)
    des mak*
    
    foreach var of varlist mak1-mak74 {
        local lab: var label `var'
        local lab = strtoname(substr("`lab'",7,.))
        rename `var' `lab'
    }
    Note that variable names cannot have spaces etc. So I have used the strtoname() function to convert those strings into legal Stata names.

    Comment


    • #3
      Thanks Hemanshu

      Comment

      Working...
      X