Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: RE: substring of a variable name


From   "Nick Cox" <[email protected]>
To   <[email protected]>
Subject   st: RE: substring of a variable name
Date   Thu, 30 Jun 2005 22:44:09 +0100

There is a command dedicated to this 
purpose, -renpfix-. 

But your attempt to do it from first 
principles is almost there. The most 
crucial detail is the lack of an 
equals sign to force evaluation. 

foreach var of varlist data* {
  	local newname = substr(`var', 5, .)
  	rename `var' `newname'
}

Another way to do it is 

foreach var of varlist data* {
  	local newname : subinstr local var "data" ""
  	rename `var' `newname'
}

In general, variable names can be manipulated 
using macros and/or string functions, just like other text. 
In fact, a large fraction of Stata depends on precisely that. 

Nick 
[email protected] 

Martin Rio
 
> I have a dataset with several variables named:
> datax1 datax2 datay1 datapt datafj
> 
> and I'd like to remove the 4 first characters of each to get variables
> with names:
> x1 x2 y1 pt fj
> 
> I tried:
> 
> foreach var of varlist data* {
>  	local newname substr(`var', 4, length(`var')-2)
>  	rename `var' `newname'
> }
> 
> It seems that the standard string functions may not apply to 
> macros. Any
> ideas on how to do this? Are there string functions specific 
> to macros? I
> was looking at the documentation for macro extended functions 
> but did not
> find something that would seem to do it.

*
*   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–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index