TeYaP
TeYaP

Reputation: 323

Rename all variable with their label values

I would like to rename all variables in my Stata dataset with their label values automatically.

Any idea of how this can be done?

Example data:

input str13 usa str9 v338 str13(fra gbr)
"1.443888e+05"  "0" "7.402382e+04"  "2.017132e+05"
"1.540046e+05"  "0" "2.091502e+05"  "1.863581e+05"
"1.339439e+05"  "0" "1.898640e+04"  "1.540931e+05"
"1.340120e+05"  "0" "6.982494e+04"  "1.554574e+05"
"1.339604e+05"  "0" "5.265134e+04"  "1.593273e+05"
"1.436713e+05"  "0" "2.477454e+05"  "2.010521e+05"
"1.339533e+05"  "0" "2.244940e+04"  "1.542236e+05"
"1.339438e+05"  "0" "1.898623e+04"  "1.540923e+05"
"3.089005e+05"  "0" "2.489533e+05"  "1.941806e+05"
"1.387412e+05"  "0" "2.759644e+04"  "1.538440e+05"

EDIT:

Do you know a way to start from the second occurrence of local macro countries? I would like to exclude the first column from the local macro list.

Upvotes: 0

Views: 1697

Answers (1)

user8682794
user8682794

Reputation:

This is how it can be done:

clear 

input str13 usa str9 v338 str13(fra gbr) 
"1.443888e+05" "0" "7.402382e+04" "2.017132e+05"
"1.364555e+05" "0" "3.683586e+05" "1.988450e+05"
"2.577159e+05" "0" "3.995106e+05" "2.113975e+05"
"1.351904e+05" "0" "2.586979e+05" "1.905737e+05"
"1.339386e+05" "0" "1.895385e+04" "1.540146e+05"
"1.517621e+05" "0" "2.021519e+04" "1.769611e+05"
"1.540046e+05" "0" "2.091502e+05" "1.863581e+05"
"1.339439e+05" "0" "1.898640e+04" "1.540931e+05"
"1.340120e+05" "0" "6.982494" "1.554574e+05" 
end 

label variable usa USA
label variable v338 Unknown1
label variable fra France
label variable gbr Britain

ds
local countries `r(varlist)'

foreach var of local countries {
    rename `var' `: variable label `var''
}

list

     +-------------------------------------------------------+
     |          USA   Unknown1         France        Britain |
     |-------------------------------------------------------|
  1. | 1.443888e+05          0   7.402382e+04   2.017132e+05 |
  2. | 1.364555e+05          0   3.683586e+05   1.988450e+05 |
  3. | 2.577159e+05          0   3.995106e+05   2.113975e+05 |
  4. | 1.351904e+05          0   2.586979e+05   1.905737e+05 |
  5. | 1.339386e+05          0   1.895385e+04   1.540146e+05 |
     |-------------------------------------------------------|
  6. | 1.517621e+05          0   2.021519e+04   1.769611e+05 |
  7. | 1.540046e+05          0   2.091502e+05   1.863581e+05 |
  8. | 1.339439e+05          0   1.898640e+04   1.540931e+05 |
  9. | 1.340120e+05          0       6.982494   1.554574e+05 |
     +-------------------------------------------------------+

I used some toy labels for the example and the command ds to obtain all the names of the variables in the dataset in a local macro.


EDIT:

Type ds usa, not instead of ds.

Upvotes: 1

Related Questions