Statalist The Stata Listserver


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

st: RE: Foreach??


From   "Nick Cox" <[email protected]>
To   <[email protected]>
Subject   st: RE: Foreach??
Date   Mon, 23 Oct 2006 23:10:26 +0100

Four comments:

1. Yes, it is being incremented by 
	local ++i 

2. Each time round the loop, however, you are setting it 
back to 1. Thus your macro goes 1, 2, 1, 2, ... 
and you are repeatedly instructing a -save- of d1.dta, 
but with different contents. 

3. Thus for what you want, the initialisation should
be moved outside the loop. 

local i = 1
foreach var of varlist I7-Q7 {
 	use edata, clear
 	keep if `var' == 1
 	bysort id (dov): gen etime = dov - dov[_n-1]
 	keep if etime > 14
 	drop etime
 	save d`i', replace
 	local ++i
}

4. But your dataset names might as well be more transparent. 
Thus your macro -i- is dispensable. 

foreach var of varlist I7-Q7 {
 	use edata, clear
 	keep if `var' == 1
 	bysort id (dov): gen etime = dov - dov[_n-1]
 	keep if etime > 14
 	drop etime
 	save d`var', replace
}

Nick 
[email protected] 

Raphael Fraser
 
> I have 12 variables I7-Q7. I would like to run the following code for
> each variable in the varlist and save the result d1, d2,  ..., d12.
> However, it appears that the macro i is not being incremented. Does
> any body know why?
> 
> My thought is each time foreach loops over a variable the macro i
> should be incremented.
> 
> foreach var of varlist I7-Q7 {
> 	use edata, clear
> 	keep if `var' == 1
> 	bysort id (dov): gen etime = dov - dov[_n-1]
> 	keep if etime > 14
> 	drop etime
> 	local i = 1
> 	save d`i', replace
> 	local ++i
> }

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