Announcement

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

  • Renaming variables with modified versions of label names

    Hello

    I have data that is set out with a first row being numbers that I would like as variable names. Since I cannot name the variables with these names (because they are digits), I would like to name my variables with the letter K in front. eg the first row appears 010 011 012 ... 200 and I would like to name the variables which fill each of their columns K010 K011 K012... K200.

    This is probably a simple thing to do but I am struggling as a new STATA user- any help would be greatly appreciated!

    Thanks

  • #2
    Here is one way. I am assuming that your variables are strings, otherwise you will not be able to have real numbers displayed as, for example, "010".

    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input str3(var1 var2 var3)
    "010" "011" "012"
    "1"   "2"   "3"  
    end
    
    ds
    foreach var of varlist `r(varlist)'{
    rename `var' K`=`var'[1]'
    }
    drop in 1

    Result:

    Code:
    . l
    
         +--------------------+
         | K010   K011   K012 |
         |--------------------|
      1. |    1      2      3 |
         +--------------------+

    Comment


    • #3
      Andrew Musau's answer is excellent, but there is still a question of why this problem arises in the first place. Often people import from a spreadsheet and they miss an option to explain that the first row of a spreadsheet contains metadata that should be used to name variables.

      As your variables are evidently string, you will have other problems with this dataset. In particular, you might need to apply destring.

      Sometimes it's easier to go back and re-do the import, but we can't be certain about that here without information on how that was done.

      If you have other problems, please do follow FAQ Advice #12 and give a data example using dataex.

      Comment


      • #4
        Originally posted by Andrew Musau View Post
        Code:
        ds
        foreach var of varlist `r(varlist)'{
        There is nothing wrong with Andrew's code; however, using ds is unnecessary.

        Code:
        foreach var of varlist * {
        
        }
        will suffice.

        Best
        Daniel

        Comment


        • #5
          Thank you all! This has been really helpful

          Comment

          Working...
          X