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: create local with specific value of a variable


From   Maarten Buis <[email protected]>
To   [email protected]
Subject   Re: st: create local with specific value of a variable
Date   Thu, 21 Feb 2013 10:03:09 +0100

--- On 2/20/2013 10:43 AM, Pablo Bonilla wrote:
>> Sometimes I need to save in a local a specific value of a variable and
>> I cannot do it because creating a local does not support “if” neither
>> “in” conditions. For instances, let’s suppose that I have two
>> variables: “x” and “y”. Variable “x” goes from 1 to 100 and “y” is a
>> random vector. Now, how can I save in a local the value of “y” when
>> “x” is, for example, 50?

--- On Wed, Feb 20, 2013 at 7:09 PM, Jeph Herrin wrote:
> In a program I would usually do this:
>
>  sum y if x==50
>  local y50 = cond(r(min)==r(max),r(min),.)
>
> which also checks that the value is unique.

That is good advise. In a program I would end up adding a bit more
bells and wistles to it:

You can make this run a bit faster by adding the -meanonly- option to
-sum-. -novariance- would probably have been a better name for the
-meanonly- option.

You can store that number with a bit more precision by storing that in
a scalar. It is almost always a good idea to use  a -tempname- for the
name of that scalar.

Such a check for equality need to be treated carefully, especially
when the value is a non-integer, again the problem is precision. I
also would check if the variable x is not a string variable. For both
we can use the -`: type <varname>'- extended macro function to extract
the type of the variable. See -help extended_fcn-.

Taking these points together I would end up with a code like this:

if substr("`: type x'",1,3)!="str" { // check that x is not a string variable
    if "`: type x'" == "float" { // check if x is stored in float precision
        sum y if x == float(50), meanonly
    }
    else { // x is either an integer or stored in double precision
        sum y if x == 50, meanonly
    }
}
else {  // x is a string variable
    sum y if x == "50", meanonly
}
tempname y50
scalar `y50' = cond(r(min)==r(max),r(min),.)

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