Statalist The Stata Listserver


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

Re: st: loop over pair of elements


From   "Tim Wade" <[email protected]>
To   [email protected]
Subject   Re: st: loop over pair of elements
Date   Sat, 16 Dec 2006 16:31:56 -0500

Caleb,

I don't think forval can be used unless the number list is in some
type of regular sequence. You could try "foreach", but you still can't
define macros two at a time. Here is something inelegant, and I'm not
sure it gets you what you want, but maybe will give you some more
ideas. you might be better of writing a program to accomplish this.
Also, once you have your code figured out you should probably use
temporary files--below I save both temporary files and permament files
with the id. Keep in mind that the temp files will not be available
after you run your do file. HTH, Tim


clear
set obs 1000
gen x=_n
gen y=_n*10

local c1 593 759
local c2 588 132
forval a=1/2 {
	preserve
	tokenize c1
	local c1x `a'
	tokenize c2
	local c2x `a'
	tempfile temp`a'
	 keep if x==`c1x'|x==`c2x'
      collapse (sum) y
	gen id=`c1x'
	save temp`a', replace
	save `temp`a'', replace
	restore
}


On 12/16/06, Caleb Southworth <[email protected]> wrote:
I have a set of pairs of observations that I would like to combine.
The new variables will be sums. This is useful, for example, when
merging historical census tracts which have been divided into two
tracts at a later time period. There are about 30 pairs of such
polygons and the operation has to be performed several times.

One solution is to identify the two observations to be merged and then
repeat this bit of code for each pair saving a temp file. For example:

local c1=593
local c2=759
keep if id==`c1'|id==`c2'
qui ds w_1888-_2004
collapse (sum) "`r(varlist)'"
gen id=`c1'
save temp1, replace

I would prefer to do this with a loop where the -foreach- command read
two strings at a time, so

forval c1 c2 = 593 759 588 132 {
        keep if id==`c1'|id==`c2'
        qui ds w_1888-_2004
        collapse (sum) "`r(varlist)'"
        gen id=`c1'
}

-forval- does not appear to work that way.

Caleb
[email protected]
University of Oregon Sociology
*
*   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/

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