Statalist The Stata Listserver


[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: RE: looping over observations


From   "Maarten Buis" <[email protected]>
To   <[email protected]>
Subject   st: RE: looping over observations
Date   Wed, 14 Mar 2007 14:44:34 +0100

--- emre ekinci wrote:
> I have 100 observations.
> 
> I want to execute some commands for each observation. here is the basic
> structure:
> 
> local i=0
>
> while `i'<=100 {
> local ++i
> 
> if ((husbage1>husbage2) | (husbage11 <husbage2)) {
> 
> stata commands
> }
>
> else {
> stata commands
> }
> 
> }
>
> if the logical statment is true for the first observation, it executes all
> commands within the if statement for other observations as well, although
> the logical statement is false for some observations.
> what is my mistake here? How can I write a loop that executes some bunch of
> commands (including if else statement)?


You would almost never ever ever have to loop over observations. But if you
are really really really sure and asked your local Stata guru (or the 
statalist) and (s)he is also really really sure that it is necessary, than 
this is how you do it:

*--------------- begin example --------------
sysuse auto, clear
gen domestic = .
local N = _N
forvalues i = 1/`N' {
	if foreign[`i'] == 0 {
		qui replace domestic = 1 in `i'
	}
	else {
		qui replace domestic = 0 in `i'
	}
}

/*but this is much quicker*/
gen domestic2 = !foreign

list domestic domestic2 in 45/56
*----------- end example ------------------

In this example I create a variable domestic which is 1 if the variable 
foreign is zero and vice versa. Notice that in the if statement there is 
[`i'] after the variable name, this will tell Stata which observation to 
look at. If you don't do that Stata will assume that you want to look at 
the first observation. 

(For more on how to use examples I sent to the Statalist, see 
http://home.fsw.vu.nl/m.buis/stata/exampleFAQ.html )

Hope this helps,
Maarten

-----------------------------------------
Maarten L. Buis
Department of Social Research Methodology 
Vrije Universiteit Amsterdam 
Boelelaan 1081 
1081 HV Amsterdam 
The Netherlands

visiting address:
Buitenveldertselaan 3 (Metropolitan), room Z434 

+31 20 5986715

http://home.fsw.vu.nl/m.buis/
-----------------------------------------



*
*   For searches and help try:
*   http://www.stata.com/support/faqs/res/findit.html
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index