I am writing a foreach loop to iterate over each variable, use its label as the new variable name, and add part of a string from its first row as the ending of its name. I.e. suppose the data looks like so:
A |
B |
C |
Dog |
Dog |
Cat |
12 |
15 |
30 |
And suppose the labels for A, B, and C are 2015, 2016, and 2017, respectively. Then the output I would like is:
2015_D |
2016_D |
2017_C |
Dog |
Dog |
Cat |
12 |
15 |
30 |
The following loop seems to work one by one:
Code:
foreach var of varlist * {
if substr(`var'[1], 1, 1) == "D" {
rename `var' `: var label `var''_D
}
if substr(`var'[1], 1, 1) == "C" {
rename `var' `: var label `var''_C
}
}
The issue I am running into is that this generally stops after each iteration and states. For instance, if I was to run it from the start on the tables above, I would get:
It seems like this is suggesting that it can't continue the loop because one of the variables was renamed and is therefore no longer in the varlist. Although, I don't see why the varlist would not update with each iteration. I tried putting this loop into another loop in order to simply repeat it many times (since it does work one by one). Any suggestions would be greatly appreciated!
0 Response to foreach rename loop keeps stopping after one loop due to variable no longer in varlist
Post a Comment