1
votes

I would like to replace and retain the original variable name after using the encode command for a set of variables x1-xn. This is where I've started:

for var x*: encode x*, generate(x*_) label(label)

My question is: what is a clean way to drop the x* (original string) variables?

When I figure that out, I can execute this command to rename x*_ (the new encoded variable):

rename x*_ x*
1
what's the question then? - djas
please add more information about your problem. - Alex Choroshin
for is not documented in any recent version of Stata. I don't have access at the moment to the documentation for Stata 6 that would be needed to answer how to do it using for, but if you are using Stata 7 or later you should switch to foreach. If you are using an earlier version, you should say what it is. If you were presenting pseudocode, you should have explained that. Whatever the truth is, this question is inadequately explained. My recollection is that your for statement is a long way from legal. - Nick Cox
@NickCox thanks for the input! I am using Stata 12, but I'm not sure what you mean by pseudocode. The commands that I posted in the question were those that I've actually used in Stata 12. My econometrics professor had used the for command in this version and it worked, so I did not realize that it was not appropriate. Could you please clarify what you meant by the pseudocode and legal comments? - Traci
Pseudocode is code that isn't in any particular language. I didn't say that using for wasn't appropriate; I said it was not documented, so you rely entirely on some code being remembered from a previous successful use. Clearly you haven't tried looking for the help for for, as you would have found that it doesn't exist. As I said, my recollection is that your code isn't legal, meaning would not work because of a syntax error. - Nick Cox

1 Answers

3
votes

Maybe you meant something like:

clear all
set more off

* example database
sysuse auto
keep make

clonevar make2 = make

describe
list in 1/5, nolabel

* what you want
foreach v of varlist make* {
    encode `v', gen(new`v')
    drop `v'
    rename new`v' `v'
}

describe
list in 1/5, nolabel

Translated into plain English (although code is straightforward) this is: for each variable that starts with make, encode it generating a new variable, then drop the old one and rename the new one. Local macros are used. See help foreach and help macro for details.