0

I would like to run a multivariate loop in Stata to rename many variables.

The following code is how i would imagine it would work:

local varlist1 "x1 x2 x3 .... xn" 
local varlist2 "a b c .... n" 

foreach i in local `varlist1' & j in local `varlist2' {
rename `i' `j'
}

The objective of this would be to rename x1 to a and x2 to b and so on.

Is there a way to do this?

1
  • As answers imply, Stata doesn't allow that syntax or anything like it. If it did it would be closer to foreach i of local varlist1 & j of local varlist2 but the form is still ambiguous whether you want all possible pairs or parallel loops. Commented Oct 19, 2018 at 11:23

3 Answers 3

1

You should not need a loop at all as

rename (x1 x2 x3 xn) (a b c n) 

is perfectly legal, given some constraints on whether the new names are in use for other variables.

Given interest in loops, here's another slow way to do it:

local new a b c n 
foreach old in x1 x2 x3 xn { 
    gettoken this new : new 
    rename `old' `this' 
} 

Here new is treated as a stack: each time around the loop, we take off the top item and do not replace it.

Sign up to request clarification or add additional context in comments.

Comments

0

Consider the following toy example:

clear
set obs 1

forvalues i = 1 / 3 {
    generate x`i' = runiform()
}

list

     +--------------------------------+
     |       x1         x2         x3 |
     |--------------------------------|
  1. | .3913819   .1196613   .7542434 |
     +--------------------------------+

Here's one way to do what you want:

local varlist1 "x1 x2 x3" 
local varlist2 "a b c" 

tokenize `varlist2'
local i 0
foreach var1 of local varlist1 {
    local ++i
    rename `var1' ``i''
}

list

     +--------------------------------+
     |        a          b          c |
     |--------------------------------|
  1. | .5844658   .3697791   .8506309 |
     +--------------------------------+

The idea here is to break up the local macro varlist2 in separate arguments 1, 2, 3 etc. and then move through them using a counter local macro i.

Alternatively, you can simply do:

local varlist1 "x1 x2 x3" 
local varlist2 "a b c" 

rename (`varlist1') (`varlist2') 

or:

rename x# (`varlist2')

Comments

0

One possible solution, certainly not the most elegant way, is to use the extended macro function word i of. A sample solution is:

local varlist1 "x1 x2 x3 .... xn" 
local varlist2 "a b c .... n" 

local numitems = wordcount("`varlist1'")

forv i=1/`numitems' {
    local old_name : word `i' of `varlist1'
    local new_name : word `i' of `varlist2'
    rename `old_name' `new_name'
} 

Comments

Your Answer

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.