I'm learning how to write a program in Stata for the first time and I'm having difficulty generalising my program so I can parse an arbitrary list of variables when renaming variables in datasets.
I'm working with two datasets. First one is panel dataset containing the life satisfaction of interviewees in a survey over a duration of 26 years (same dataset as in my previous question). The variables are originally named in this format: ap6801 bp9301 cp9601 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 wrote the following program to rename the variables so instead of ap6801 it would be lsat1985.
program myprogram
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'* lsat`mcode'
}
Now, I want to modify and generalise this program so that I can use it on my second dataset and with arbitrary numbers. The second dataset consists of variables abetto bbetto cbetto all the way until zbetto. These variables indicate whether a specific person has been interviewed in a specific year and, if not, why not. abetto corresponds to year 1985, bbetto corresponds to year 1986, and so on.
My goal is to write a generalised version of the program so that when I enter an arbitrary list of variables and other information (for example lsat, and a list of numbers (eg: 1985-2010)): myprogram ap6801-zp15701 , the variables will be renamed lsat1985 lsat1986... lsat2010
I'm guessing the program will have the following basic structure:
program myprogram
syntax varlist
foreach x of varlist {
}
Within the loop, there might be local letter = substr("`x'",1,1) to identify the first letter of the variables (a, b, c, d...). Next step would be to link the letters of the alphabet to numbers that will be specified by the user, and a rename command that renames the variable in the format: lsat/betto year. I'm having a difficult time putting all that together in code.
I'm new to Stata and programming, so any help is appreciated!