Announcement

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

  • Saving variable name into a local

    Hey,

    I have a dataset with many lengthy variable names but which are useful for identification. What I would like to do is the following:
    Loop through the variables.
    1. Store the name of the variable to a local
    2. rename the variable as var1
    3. give the renamed variable the label of the old variable

    What I have been struggling is that when using foreach var of varlist and then looping through, it goes through the values.
    I would like to store the name of the variable. I have looked at past posts and the help manual but have not been able to find anything regarding this.
    Pseudocode as answer would be appreciated. Thank you in advance.

    Code:
    scalar temp= 1
    foreach var of varlist _all {
    //save variable name to local ( say i e.g.)
    rename `var' var`temp'
    label var`temp' `i'
    scalar temp= `temp' + 1




  • #2
    Here is a convenient way to do this (that requires elabel from SSC).

    Code:
    unab vars : *
    elabel variable (`vars') (`vars')
    rename (*) (var#) , addnumber

    And here is your loop:

    Code:
    local i 0
    foreach var of varlist _all {
        label variable `var' `var'
        local i = `i' + 1
        rename `var' `var'`i'
    }
    Note that you loop over the variable names; therefore, there is no need at all to store the variable name into an additional local macro; the name is already store in `var'.
    Last edited by daniel klein; 22 Jan 2021, 11:44. Reason: add loop as requested

    Comment


    • #3
      I'm not sure that step 1 is necessary. You already have access to the variable names via the loop, so why not just label variable with its own name and then rename it to var`temp'?

      Code:
      clear
      input thisisaverylongname thisisanevenlongername thisnameisincrediblylong
      . . .
      end
      local temp 1
      foreach var of varlist _all {
          label variable `var' `var'
          rename `var' var`temp'
          local ++temp
      }
      
      . describe
      
      Contains data
        obs:             1                          
       vars:             3                          
      ----------------------------------------------------------------------------------------------------------------------------
                    storage   display    value
      variable name   type    format     label      variable label
      ----------------------------------------------------------------------------------------------------------------------------
      var1            float   %9.0g                 thisisaverylongname
      var2            float   %9.0g                 thisisanevenlongername
      var3            float   %9.0g                 thisnameisincrediblylong
      ----------------------------------------------------------------------------------------------------------------------------
      Last edited by Ali Atia; 22 Jan 2021, 11:43.

      Comment


      • #4
        Only one variable can be (re)named var1 -- but your code makes it clear that you want variables to be called var1 var2 and so forth. Or, rather, you do need a loop but rename will oblige.

        Such colourless names I don't recommend, but you can do it and you don't need a loop.

        Code:
        . sysuse auto, clear
        (1978 Automobile Data)
        
        . ds
        make          mpg           headroom      weight        turn          gear_ratio
        price         rep78         trunk         length        displacement  foreign
        
        . rename * var#, renumber
        
        . ds
        var1   var2   var3   var4   var5   var6   var7   var8   var9   var10  var11  var12
        
        . d
        
        Contains data from C:\Program Files (x86)\Stata\ado\base/a/auto.dta
          obs:            74                          1978 Automobile Data
         vars:            12                          13 Apr 2018 17:45
                                                      (_dta has notes)
        ------------------------------------------------------------------------------------------------------
                      storage   display    value
        variable name   type    format     label      variable label
        ------------------------------------------------------------------------------------------------------
        var1            str18   %-18s                 Make and Model
        var2            int     %8.0gc                Price
        var3            int     %8.0g                 Mileage (mpg)
        var4            int     %8.0g                 Repair Record 1978
        var5            float   %6.1f                 Headroom (in.)
        var6            int     %8.0g                 Trunk space (cu. ft.)
        var7            int     %8.0gc                Weight (lbs.)
        var8            int     %8.0g                 Length (in.)
        var9            int     %8.0g                 Turn Circle (ft.)
        var10           int     %8.0g                 Displacement (cu. in.)
        var11           float   %6.2f                 Gear Ratio
        var12           byte    %8.0g      origin     Car type
        ------------------------------------------------------------------------------------------------------
        Sorted by: var12
             Note: Dataset has changed since last saved.


        Note that you don't do anything with the variable labels, as they remain the same.
        Last edited by Nick Cox; 22 Jan 2021, 11:48.

        Comment


        • #5
          Code:
          sysuse auto, clear
          
          local i = 0
          foreach v of varlist _all {
              local ++i
              local original_name_`i' `v'
              rename `v' var`i'
          }
          
          macro dir
          Note: There is nothing wrong with using a scalar instead of a local macro to track the numbering. I just find locals more convenient and the code a bit cleaner.

          Added: Crossed with #2 and #3.

          Comment


          • #6
            Thank you for quick replies. It works as I wished it to work. I tried the solutions proposed by Nick Cox and Ali Atia. I didn't try because Klein's solution as I didn't want to install it if it can be done without.

            Ali's solutions worked just right of the bat. I wasn't able to get Nick's solution to work. More precisely, it renamed the vars but didn't create a label that is equal to the old name of the variable. I suppose that this is because Nick thought that the labels were preexisting as he mentioned "Note that you don't do anything with the variable labels, as they remain the same." (or, more probably, because I didn't follow his code snippet properly.)



            Comment


            • #7
              Just by way of clarification, there was nothing to install in my suggested code in #5. I'm not sure what you are thinking of. Perhaps the -sysuse auto, clear- command confused you? The auto.dta is already installed: it's a part of official Stata and is installed when you install Stata itself. And that command played no role in how the solution works: it was just there to provide a demonstration of how the code works.

              Had you tried my code, you would have found that, like Nick's, it fails to label the variables with the old variable name. For some reason, I just forget about that part, though it would have been very easy to add one line to the code that would have accomplished it.

              Anyway, glad your problem is solved. Just wanted to clear up some possible confusion.

              Comment


              • #8
                #1 point 3 asked that the new variable name goes with the old variable label.

                Wanting the old name to be the new variable label is not what I understood you to be asking.

                Comment

                Working...
                X