问题
I am trying to create locals on the fly and check them by assigning values to a new variable
gen sampleVar =.
foreach i in AK AL AR AZ {
su income if (year==2012 & state_nsw == "`i'"), meanonly
local val_`i' = r(mean)
display "`val_`i''"
}
// check the local
recode sampleVar .= "`val_AL'"
// this is what I get:
5242.57421875
.....
5352.66796875
. invalid name
r(198);
// check 2 the local
recode sampleVar .= `val_AL' // error
ANSWER: My problem was that I tried
recode sampleVar .= `val_AL' + `val_AZ'
// this is inappropriate.
//the correct way is:
local try = `val_AL' + `val_AZ'
recode sampleVar .= `try'
回答1:
Be clear that your local
s must be in the same name space, i.e. interactive session, do-file, do-file editor, program. To debug, type
macro li
before the recode
statement to see what macros are visible.
来源:https://stackoverflow.com/questions/17266287/how-to-create-locals-on-the-fly-in-stata