Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: RE: Renaming varnames


From   "Nick Cox" <n.j.cox@durham.ac.uk>
To   <statalist@hsphsun2.harvard.edu>
Subject   st: RE: Renaming varnames
Date   Wed, 25 Jan 2006 21:23:31 -0000

Your loop is a good idea, except
that putting the name in a new variable
is not the best way to do it. 
And there is no point in doing this 
for _all_ variables. Perhaps there 
are some other problems too. 

My official Stata solution: 

foreach v of var *_ { 
	local V : subinstr local v "_" "", all
	capture rename `v' `V' 
	if _rc di as txt "problem with `v'"
} 

User-written program: 

renvars *_, map(substr("@", 1, index("@","_") - 1))

(-renvars- was last updated in Stata Journal 5(4).) 

Bail out now if this is transparent. 

Otherwise: 

*_ catches all variable names that end with an underscore. 

-capture- traps any problem inside the loop and lets it continue. 

-renvars- won't rename any variable unless all new variable names are
OK (legal and unambiguous). 

The rule for a new name is 

substr("@", 1, index("@","_") - 1)

namely, start at the beginning and stop just before the first underscore. 

Nick 
n.j.cox@durham.ac.uk 

> -----Original Message-----
> From: owner-statalist@hsphsun2.harvard.edu
> [mailto:owner-statalist@hsphsun2.harvard.edu]On Behalf Of 
> Thomas Speidel
> Sent: 25 January 2006 20:46
> To: statalist@hsphsun2.harvard.edu
> Subject: st: Renaming varnames
> 
> 
> I have a dataset whose variable names contain a varying amount of
> trailing underscores (_).
> Is there a way to rename all variable names without the trialing
> underscores (other than renaming each individual variable)?
> 
> ILLNESS___      byte   %10.0g                 
> SPECIMEN__      str12  %12s                   
> HOSPITAL__      byte   %10.0g                 
> TYPE______      byte   %10.0g                 
> STAGE_____      str4   %9s                    
> SIZE______      byte   %10.0g           
> ...
> 
> This is what I have tried so far (unsuccessfully):
> 
> 
> foreach v of varlist _all {
> 	gen `v'_underscore=strpos("`v'", "_")
> 	rename `v' `=substr("`v'", 1, `v'_underscore)'
> }
> 

*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2021 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index