Reputation: 23
I need to rename my variables var1
to var60
into var2
to var61
(i.e. doing +1 for the suffix of each variable, so that var2
becomes var3
, var3
becomes var4
...and so on).
I tried several things (renvars
, rename
), but I did not succeed and I am not very good at doing loops with foreach
...
Upvotes: 2
Views: 1224
Reputation: 37183
It is also possible to go backwards:
forval i = 60(-1)1 {
local j = `i' + 1
rename var`i' var`j'
}
This replaces two loops, as suggested by @Metrics, with one. Those paid by the reciprocal of the number of lines of code will want to go instead
forval i = 60(-1)1 {
rename var`i' var`=`i' + 1'
}
Upvotes: 2
Reputation: 15458
Here is a two step approach
forvalues i =1/60{
rename var`i' var`=`i'+10'
}
forvalues i =11/70{
rename var`i' var`=`i'-9'
}
Example with auto data:
sysuse auto
rename make var1
rename price var2
rename mpg var3
forvalues i =1/3{
rename var`i' var`=`i'+10'
}
forvalues i =11/13{
rename var`i' var`=`i'-9'
}
Upvotes: 2