Announcement

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

  • Rename variables numerically through loop

    Hello,

    I am trying to rename all variables in my dataset to something informative, rather than r4, r5,....rn. The "r's" correspond to years, and they are in sequence. So I would like to have something like:

    Code:
    rename r4 yr_1926
    rename r5 yr_1927
    rename r6 yr_1928
    .
    .
    .
    rename r76 yr_2002
    I tried to use a loop like the following (and different variations) and keep getting to the same problem. I can't figure out how to get it to exit the second loop and pick the next year.
    Code:
    foreach i of numlist 1926/2002{
    foreach x of varlist *{
             local i = `i' 
             rename `x' var`i'
    }
    }


    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input long id double(r4 r5 r6 r7 r8)
    10006  67.743  71.245  70.139  70.139  70.139
    10014  13.005  12.787   12.63  13.871  14.896
    10022  13.567  13.996  14.326  14.552  14.025
    10030  15.924  17.487  18.771  20.508  20.488
    10049  11.984  12.848   13.34  59.145  61.094
    10057   8.234   8.376   8.448   7.577   8.966
    10065  16.609  15.727  13.849  18.062  -99.99
    10073  14.789  14.912  14.571  15.321  14.926
    10081   1.769    1.83   1.881   1.731   1.703
    10102  14.474  16.604  19.184   21.49  27.895
    10110  10.767  10.474  10.699   9.168   5.695
    10129  37.706  -99.99  -99.99  -99.99  -99.99
    10137  17.636  20.783  71.325  74.917  79.579
    10145 161.283 172.804 181.573 192.716 207.096
    10153  40.259  41.155  40.554  41.733  47.277
    10161  29.267  29.237  29.332  39.581  45.541
    10188  10.207   8.021   8.412   9.452  10.382
    10196  -99.99  -99.99  -99.99  -99.99  -99.99
    10209  15.462  16.486  14.561  16.589  17.205
    10217  11.168  11.544  12.234  12.952  13.742
    end

  • #2
    No need for loops here.
    Code:
    rename r# yr_#, renumber(1926)

    Comment


    • #3
      Thank you! I didn't realize that the rename function had so much flexibility

      Comment


      • #4
        What I showed you in #2 barely scratches the surface of what -rename- can do. Read -help rename group-. You'll be amazed.

        Comment


        • #5
          For the record, note an extra problem: #1 showed a nested loop, but you want one loop over two lists in parallel. In principle, something like

          Code:
          local y = 1926
          foreach v of var r* {
                rename `v' yr_`y'
                local ++y
          }
          would have been one of several other ways to do it.

          Pedantry corner: rename is a command, not a function.




          Comment

          Working...
          X