Announcement

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

  • assign variable label to variable name

    Hi
    I have a dataset that has some variables, say, X1-X10. The corresponding variable labels are 2018:q1, 2018q2, and so on. i want to rename the variables and set their labels as the new name, such that my new variable names be something like var_2018_q1, var_2018_q2, etc. I would appreciate it if anyone can help.

    Thanks,

  • #2
    Code:
    //    CREATE A DEMONSTRATION DATA SET
    clear*
    set obs 1
    forvalues i = 1/10 {
        gen x`i' = .
    }
    
    //    DO THE REQUESTED RENAMING
    forvalues i = 1/10 {
        local date: display %tqCCYY!_!qq tq(2017q4) + `i'
        label var x`i' "`date'"
        rename x`i' var_`date'
    }

    Comment


    • #3
      Originally posted by Clyde Schechter View Post
      Code:
      // CREATE A DEMONSTRATION DATA SET
      clear*
      set obs 1
      forvalues i = 1/10 {
      gen x`i' = .
      }
      
      // DO THE REQUESTED RENAMING
      forvalues i = 1/10 {
      local date: display %tqCCYY!_!qq tq(2017q4) + `i'
      label var x`i' "`date'"
      rename x`i' var_`date'
      }

      My variables have labels. See below (sorry if this is not the best way of listing the 'd' command):

      v53 long %12.0g 2009:Q1
      v54 long %12.0g 2009:Q2
      v55 long %12.0g 2009:Q3
      v56 long %12.0g 2009:Q4
      v57 long %12.0g 2010:Q1
      v58 long %12.0g 2010:Q2
      v59 long %12.0g 2010:Q3
      v60 long %12.0g 2010:Q4
      v61 long %12.0g 2011:Q1
      v62 long %12.0g 2011:Q2
      v63 long %12.0g 2011:Q3
      v64 long %12.0g 2011:Q4


      I have 100 variables.

      Comment


      • #4
        Try

        Code:
        forval i=1/100{
            rename v`i' v`=strtoname("`:var lab v`i''")'
        }
        Last edited by Andrew Musau; 26 Apr 2023, 23:33.

        Comment


        • #5
          Originally posted by Andrew Musau View Post
          Try

          Code:
          forval i=1/100{
          rename v`i' v`=strtoname("`:var lab v`i''")'
          }
          Worked perfectly. Thank you very much, Andrew!

          Bests,

          Comment


          • #6
            Although ,you got what you asked for, duty obliges a comment that a wide layout like this is of limited use for Stata analyses. For example, even a graph of a single series is extraordinarily hard. But you may have a special purpose in mind. reshape long for most Stata purposes with data in time.

            Comment

            Working...
            X