I have a Stata dataset with variable labels describing the year of measurement. I need to access the year of measurement from the variables to later rename each variable using a suffix showing the year. For example V95
has a label GNP/CAPITA,75
, and I want to rename it to gnp_capita_75
. Some variables have labels like GNP/C:GROWTH RTS,60-75
, and I want to add the midpoint of the interval after the comma to the variable name.
So far my code for accessing the variable labels looks like this:
local varlist V1 V2 V3 V28 V29 V30 V85 V86 V87 V88 V89 V90 V91 V92 V93 V94
foreach variable in `varlist' {
//get the label of the variable
local label : var label `variable'
//find the position of the comma
local commapos : strpos(`label', ",")
//find the stub before the comma
local namestub : substr(`label', 1, `commapos' - 1)
//find year after the comma
local year : substr(`label', `commapos' + 1, `commapos' + 2)
//replace any illegal character (%,/,:," ") with underscores:
local namestub : subinstr(`namestub', "%", "_")
local namestub : subinstr(`namestub', "/", "_")
local namestub : subinstr(`namestub', ":", "_")
local namestub : subinstr(`namestub', " ", "_")
//rename variable with the new stub and the year
rename `variable' `namestub'`year'
}
I get an error saying that strpos() is not allowed. Is it because I'm trying to make that a local macro? The examples I saw use it to generate a variable in the dataset, but I'm dealing with the variable labels. Am I in the right direction here? How do I fix this error?
help strtoname()
for replacing characters not allowed in Stata names. – Roberto Ferrer