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: combine foreach and if


From   Nick Cox <[email protected]>
To   "[email protected]" <[email protected]>
Subject   Re: st: combine foreach and if
Date   Tue, 4 Mar 2014 20:13:33 +0000

I think you are confusing the -if- command and the -if- qualifier. The
key point is that two code segments are in no sense alternatives, as

if time == `TIME' {
}


will always be interpreted as

if time[1] == `TIME' {
}

which is evidently not what you want. This is documented at

FAQ     . . . . . . . . . . . . . . . . . . . . if command versus if qualifier
        . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .  J. Wernow
        4/05    I have an if or while command in my program that
                only seems to evaluate the first observation.
                What's going on?
                http://www.stata.com/support/faqs/programming/
                if-command-versus-if-qualifier/


Otherwise put, your stylistic preferences collide with Stata's syntax
rules and that's an unequal contest.

In any case I don't understand quite what is your objection to the
second form. If you have other code to be carried out for all data
points, then quite simply it doesn't belong in the -foreach- block.

You will probably need to say more about what you want to do in the
rest of the code to get better advice.

Nick
[email protected]


On 4 March 2014 20:02, Vincent Koppelmans <[email protected]> wrote:

> I want to loop over a couple of time points in a dataset and filer out certain rows.
> I tried to combine a foreach loop with an if statement, but it is not working (it only prints the results using the first value of the numlist):
>
>
> foreach TIME of numlist 1 5 {
> if time == `TIME' {
> summ DS_sec_
> plot DS_sec_ Subject_ID
> }
> }
>
>
> The following code however is working:
>
> foreach TIME of numlist 1 5 {
> summ DS_sec_ if time == `TIME'
> plot DS_sec_ Subject_ID if time == `TIME'
> }
>
> In this simple example the syntax does not differ a lot in length, but the actual code that needs to be executed is much longer. I therefore would prefer a solution that resembles my initial code, because that would mean that I do not have to add the "if time == `TIME'" part after each line.
>
> How can I do this?

*
*   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