Bookmark and Share

Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.


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

Re: st: Shortening variable names loop problem


From   Maarten Buis <[email protected]>
To   [email protected]
Subject   Re: st: Shortening variable names loop problem
Date   Thu, 19 Sep 2013 10:12:12 +0200

On Thu, Sep 19, 2013 at 9:39 AM, George Murray wrote:
> I am trying to shorten all variables with 31 or 32 characters to 30 by
> removing the last 1 or 2 characters.

Here is an example that cuts the variable names at the fifth character:

*------------------ begin example ------------------
sysuse nlsw88, clear
foreach var of varlist * {
    rename `var' `=substr("`var'",1,5)'
}
*------------------- end example -------------------
* (For more on examples I sent to the Statalist see:
* http://www.maartenbuis.nl/example_faq )


> Does any one know why the
> following command does not work (type mismatch):
>
> foreach var of varlist * {
> replace `var' = "substr("`var'",1,30)"'
> }

-replace- changes the content of the variable not its name, so that
would not do what you want. Also you start the expression after = with
" and end it with "' and they do not match. Finally, by declaring the
part after the = as a string (by surrounding it with ") you explicitly
state that you do not wish to have that function evaluated, which is
probably not what you want.

> Replacing the second line with -rename `var' "substr("`var'",1,30)"-
> also doesn't work (parenthesis unbalanced).

-rename- is correct, but you need to make sure that the -substr()-
function is evaluated before Stata starts with -rename-. -rename-
needs to see the result of -substr("`var'",1,30)-, instead it sees
literaly "substr("<variable name>",1,30)", which is an invalid
variable name, and Stata returns an error.

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–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index