3

I have the following dataset:

* Example generated by -dataex-. To install: ssc install dataex
clear
input float(MA_234_AAF_US AL_87665_ACH_USA TX_3_GH_US LA_689_KLO_US KY_3435_Z_USA)
  9.96567 10.559998 12.935112 13.142867   9.35608
 9.758375     9.856 10.002945  8.090142 10.313352
11.594983  9.274136 12.486753  6.661111 10.529528
10.354564  9.893115 10.625778 13.265523  7.405652
  12.7978  10.76272 11.527348 10.112844  11.64973
 10.63846 11.040354  8.569465  8.781206 11.448466
 9.254233 13.808356 10.817062  9.545164  8.759109
  11.8417  10.15155  12.72436 11.102546 11.506034
 9.864883  9.864952  14.45111  10.12562  9.753519
 9.965327 11.517155  9.910269  8.988406 11.359774
end

I would like to change the order of the text in the variable names like this:

US_MA_AAF_234   USA_AL_ACH_87665   US_TX_GH_3   US_LA_KLO_689   USA_KY_Z_3435

I have tried the code provided in the answers in this question:

However, I could not make it work.

1 Answers1

1

Here is an alternative approach.

It's inferior to using rename in one line, which addresses the purpose well. Scrutiny will show the necessary correspondence with that approach. It hinges on the names being elements separated by underscores, which are removed and then reinserted.

clear
input float(MA_234_AAF_US AL_87665_ACH_USA TX_3_GH_US LA_689_KLO_US KY_3435_Z_USA)
  9.96567 10.559998 12.935112 13.142867   9.35608
end

foreach name of var * { 
    local new = subinstr("`name'", "_", " ", .) 
    tokenize `new' 
    rename `name' `4'_`1'_`3'_`2' 
}

describe, fullnames 

Contains data
  obs:             1                          
 vars:             5                          
 size:            20                          
-------------------------------------------------------------------------------------------
              storage   display    value
variable name   type    format     label      variable label
-------------------------------------------------------------------------------------------
US_MA_AAF_234   float   %9.0g                 
USA_AL_ACH_87665
                float   %9.0g                 
US_TX_GH_3      float   %9.0g                 
US_LA_KLO_689   float   %9.0g                 
USA_KY_Z_3435   float   %9.0g                 
-------------------------------------------------------------------------------------------

EDIT:

As @PearlySpencer points out, the statements within the loop

local new = subinstr("`name'", "_", " ", .) 
tokenize `new' 
rename `name' `4'_`1'_`3'_`2' 

could be replaced by

tokenize `name', parse(_)
rename `name' `7'_`1'_`5'_`3' 

The difference is that the underscores will get placed in local macros 2, 4, 6.

Nick Cox
  • 35,529
  • 6
  • 31
  • 47