There is no need here to invoke regular expressions. You have the new suffixes; the prefix pkg
is always the same, so the labour of extracting it repeatedly is unnecessary. The heart of the problem is cycling over two lists at once. Here is one way to fix your code.
local croplist mz gmz sp sptc mil cof suk tea ric
local j = 1
foreach x of varlist pkg* {
local sffx : word `j' of `croplist'
rename `x' pkg`sffx'
label var pkg`sffx' "Avg district level `sffx' price"
local ++j
}
Note also rename
in Stata 12+ can handle this; regexr()
is a function, not a command; a more general discussion in http://www.stata-journal.com/sjpdf.html?articlenum=pr0009 (a little out-of-date, but relevant on the main issue); you have too many quotation marks on your rename
command, so it wouldn't work.
EDIT 30 July 2018
I tend now more often to use gettoken
:
local croplist mz gmz sp sptc mil cof suk tea ric
foreach x of varlist pkg* {
gettoken sffx croplist: croplist
rename `x' pkg`sffx'
label var pkg`sffx' "Avg district level `sffx' price"
}
The local macro croplist
is a stack. Each time around the loop we take the top item from the stack and leave the rest for the next time.
Each time around the loop