In Stata, I have a set of variables that all begin with pkg
. In their current state, their endings are numeric: pkg1
, pkg2
, pkg3
, pkg4
and so on.
I need to change all of these variables' endings to strings: pkgmz
, pkggmz
, pkgsp
, pkgsptc
etc.
I have a column of these string endings, which I can designate as a local list.
For example:
local croplist mz gmz sp sptc mil cof suk tea ric
How do I change the numeric endings to the string endings?
My guess at the code can be found below and the ???
indicate where I am stumped:
local croplist crops mz gmz sp sptc mil cof suk tea ric
foreach x of varlist pkg* {
local new1 = substr(`x', 1, 3)
local new2 = ???
rename `x' ``new1'`new2''
label var ``new1'`new2'' "Avg district level `new2' price"
}
I wonder if it would be better to utilize the regexr()
command, but can't think of a way to include it.
Any help is appreciated.
Here is another way to do it. tokenize
puts separate words in macros numbered 1 up. The nested reference ``j''
is handled just in elementary algebra: evaluate the inside macro reference first.
tokenize "mz gmz sp sptc mil cof suk tea ric"
forval j = 1/9 {
rename pkg`j' pkg``j''
label var pkg``j'' "Avg district level ``j'' price"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With