Bookmark and Share

Notice: On March 31, it was announced that Statalist is moving from an email list to a forum. The old list will shut down at the end of May, and its replacement, statalist.org is already up and running.


[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 <njcoxstata@gmail.com>
To   statalist@hsphsun2.harvard.edu
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 <mayankm16@gmail.com> 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–2014 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   Site index