Keep track of original variable name after rename using notes stata

Viewed 116

I am working with a panel dataset containing the life satisfaction of interviewees in a survey. There are 26 variables for the respondent's life satisfaction (for 26 years). The variables are originally named in this format: ap6801 bp9301 cp9601 dp9801 and all the way to zp15701. ap6801 contains the respondents' life satisfaction for the year 1985, bp9301 contains it for 1986, and so on.

I created a foreach loop to rename the variables so that they are now in the pattern: lsatyear (i.e. lsat1985, lsat1986, ...)

local mcode 1984
foreach stub in a b c d e f g h i j k l m n o p q r s t u v w x y z {
    local mcode = `mcode' + 1
    rename `stub'p* lsat`mcode'
}

Now, I want to keep track of the original variable names (ap6801, bp9301, etc.) by adding a command to my loop using the notes command of Stata. If I were to do it manually, the following command works:

notes lsat1985 : ap6801

But is there a way to add it to my loop? I came across a Stata 13 manual for renaming variables and at the end there is a section about stored results:

rename stores nothing in r() by default. If the r option is specified, then rename stores the following in r(): .... Macros r(oldnames) original variable names r(newnames) new variable names

I tried r(oldnames) on a single variable after renaming it

rename ap6801 lsat1985
notes lsat1985 : r(oldnames)

but it gives me an error:

factor-variable and time-series operators not allowed r(101);

I'm new with Stata and loops, so any help is appreciated!

1 Answers

You need to actually use the r option, and call the local macro r(oldnames) instead of passing the string r(oldnames).

Instead of:

rename ap6801 lsat1985
notes lsat1985 : r(oldnames)

try

rename ap6801 lsat1985, r
notes lsat1985 : `r(oldnames)' // note wrapping in `' indicates a local
Related