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: Min value of a variable and an error in for loop


From   Nick Cox <[email protected]>
To   [email protected]
Subject   Re: st: Min value of a variable and an error in for loop
Date   Mon, 27 Jun 2011 09:38:30 +0100

-summarize val- will give you the minimum (and other stuff) directly.
You can pick up the minimum afterwards as r(min).

This code is close in spirit to what you did but is also legal

local minval = val[1]
forvalues i = 2/`=_N' {
     if val[`i'] < `minval'  local minval = val[`i']
}

What you did wrong:

1. Putting constants in variables. Legal, but poor style usually.

2. Expecting -forval- to evaluate _N on the fly. Not unreasonable but
won't work.

3. Mixing syntax for values and locals. `temp[1]' won't work. `temp
[1]' won't work.

4. Using temp and minval for the same thing. Legal, but poor style usually.

But you should just use -summarize- directly.

Nick

On Sun, Jun 26, 2011 at 5:13 PM, Mayank Mishra <[email protected]> wrote:

> I need to find out the minimum value observation of a variable. I
> tried the following loop to obtain it:
>
> gen temp = val[1]                                // val is the
> variable whose min value i intend to find
> forvalues i=2/_N {
> replace temp = val[`i'] if val[`i']<`temp[1]'
> }
> gen minval = `temp [1]'
>
> the message i got was invalid syntax. Please tell me the problem with
> this loop. I also tried
>
> local temp
>
> , instead of "gen temp" in first line, but got the same result.
>
> Also, please tell me, if there is some other more efficient method to do this.

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


© Copyright 1996–2018 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   Site index