2

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?

asked May 26, 2014 at 10:16
1
  • 1
    See help strtoname() for replacing characters not allowed in Stata names. Commented May 26, 2014 at 15:02

1 Answer 1

3

The syntax you need is

local commapos = strpos("`label'", ",")` 

and similarly for substr().

Note the extra bug that you need to enclose the label text in " ". That is needed elsewhere too.

The colon syntax is for extended macro functions, not functions in general.

(Learning how to automate this is a good ambition, but if the problem is this size, using varm interactively would have been quicker.)

answered May 26, 2014 at 10:58
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the replies and the comments. The problem is a little larger, as I have about ten times more variables than I put in the question (to save space). Therefore I don't want to use the variables manager.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.