Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down on April 23, and its replacement, statalist.org is already up and running.


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: st: Batch renaming variables


From   Maarten Buis <maartenlbuis@gmail.com>
To   statalist@hsphsun2.harvard.edu
Subject   Re: st: Batch renaming variables
Date   Thu, 18 Oct 2012 16:02:12 +0200

On Thu, Oct 18, 2012 at 3:36 PM, Wameq Raza wrote:
> To elaborate, suppose I have 10 variables: v1, v2....v10 and I want to
> rename every second var (ie v2, v4, v6, v8 and v10) to cost_a,
> cost_b....cost_e.

Below I make heavy use of the extended macro function as documented in
-help extended_fcn-

*------------------- begin example -----------------
// create some example data
clear
set obs 10
forvalues i = 1/10 {
	gen v`i' = runiform()
}

// do the rename
local j = 0
forvalues i = 2(2)10 {
	// which letter from the alphabet
	local j = `j' + 1
	
	// c(alpha) contains a string containing the
	//space-separated list of lowercase letters.
	local letter : word `j' of `c(alpha)'
	
	// create the new name
	local newname "cost_`letter'"
	
	// do the rename
	rename v`i' `newname'
}

// alternatively all in one
clear
set obs 10
forvalues i = 1/10 {
	gen v`i' = runiform()
}

local j = 0
forvalues i = 2(2)10 {
	rename v`i' cost_`: word `++j' of `c(alpha)''
}
*-------------------- end example ------------------
(For more on examples I sent to the Statalist see:
http://www.maartenbuis.nl/example_faq )

Hope this helps,
Maarten

---------------------------------
Maarten L. Buis
WZB
Reichpietschufer 50
10785 Berlin
Germany

http://www.maartenbuis.nl
---------------------------------
*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/faqs/resources/statalist-faq/
*   http://www.ats.ucla.edu/stat/stata/


© Copyright 1996–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index