Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: st: Renaming variables using foreach
From
Nick Cox <[email protected]>
To
[email protected]
Subject
Re: st: Renaming variables using foreach
Date
Tue, 26 Jun 2012 22:45:59 +0100
Working backwards,
0. Your example sounds like a very bad idea. Your variables have names
that mean something; you want instead to impose arbitrary and
meaningless names. I am reminded of learning MINITAB some decades ago
and finding that I could call my columns [sic] anything I wanted so
long as it was something like C1, C2, C3.... (At least that it is what
I recall.)
1. In Stata 12, -rename- is now so versatile that writing your own
-foreach- loop shouldn't be necessary for renaming.
2. Personally, I still tend to reach for -renvars- (SJ) because I
internalised most of the syntax over ten years of using it.
3. What's wrong with your -foreach- loop?
local i = `i' + 1
foreach x of varlist <whatever> {
rename `x' var`i'
}
Evidently local macro -i- was not mentioned before this code. Thus you define
local i = `i' + 1
On the right-hand side you reference a local macro which does not yet
exist. That is OK by Stata. It merely subsitutes the references by
nothing. The expression now reads
local i = +1
which is OK by Stata. It does the arithmetic, +1 evaluates to 1, and
the local macro -i- is born as the string "1". For all the difference
it makes, you could have written
local i "1"
or
local i = 1
The crucial point is this. You've defined the local macro once, but
once in the loop you never change it. (So, this bites second time
around the loop, when -rename- to -var1- fails because -var1- already
exists.)
Or, to put it more directly, the local macro (re-)definition belongs
_inside_ the loop, so that the incrementation takes place as you want
(and need).
foreach x of varlist <whatever> {
local i = `i' + 1
rename `x' var`i'
}
Nick
On Tue, Jun 26, 2012 at 10:20 PM, Suryadipta Roy <[email protected]> wrote:
> I am currently learning looping in Stata and is stuck with the
> following problem: I have about 150 variables that I want to rename as
> var1 var2, etc.. upto var 150. I tried the following:
>
> local i = `i' + 1
> foreach x of varlist Agricultural_raw_materials_expor -
> Value_lost_due_to_electrical_out {
> 2. rename `x' var`i'
> 3. }
>
> I am getting the following error message:
> var1 already defined
> r(110);
>
> I find that only the first variable is renamed as "var1" and then the
> loop stopped running. Any help is greatly appreciated.
*
* For searches and help try:
* http://www.stata.com/help.cgi?search
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/