Notice: On April 23, 2014, Statalist moved from an email list to a forum, based at statalist.org.

RE: st: simulataneous foreach loops

 From Nick Cox To "'statalist@hsphsun2.harvard.edu'" Subject RE: st: simulataneous foreach loops Date Tue, 16 Nov 2010 11:50:25 +0000

```The first solution shows an impressive grasp of technique, but it's a bit like building a tank so that you can drive to the nearest convenience store. The second solution and Nick Winter's solution

local tnums 101 102 103
local tsizes 3 5 3

forval i=1/3 {
local team : word `i' of `tnums'
local size : word `i' of `tsizes'
di "Team `team' will have `size' members"
}

show that the same ends can be achieved with much simpler machinery.

Nick
n.j.cox@durham.ac.uk

. do C:\temp\listdbl.do

.
. // ------------ SOLUTION WITH CLASSES ---------------
.
. class bstrap_plan {
.   array teams = {102,108,202}
.   array membs = {  3,  5,  3}
. }

.
. .P=.bstrap_plan.new

.
. local npairs `.P.teams.arrnels'

. forvalues i=1/`npairs' {
2.
.        local team `.P.teams[`i']'
3.        local memb `.P.membs[`i']'
4.
.        preserve
5.        //bsample `memb'
.        //replace team=`team'
.        //save simteam_`team'.dta, replace
.                 display `team' "  " `memb'
6.        restore
7. }
102  3
108  5
202  3

.
.
. // ------------ SOLUTION WITH MATRICES --------------
. matrix P = 102,3\108,5\202,3

.
. local npairs=rowsof(P)

. forvalues i=1/`npairs' {
2.
.        local team=P[`i',1]
3.        local memb=P[`i',2]
4.
.        preserve
5.        //bsample `memb'
.        //replace team=`team'
.        //save simteam_`team'.dta, replace
.                 display `team' "  " `memb'
6.
.        restore
7. }
102  3
108  5
202  3

.
.
end of do-file

And as a bonus we get the plan matrix in a readable form (add row and
column headers to taste):

. matrix list P

P[3,2]
c1   c2
r1  102    3
r2  108    5
r3  202    3

Best, Sergiy

PS: uncomment the bootsrap part in both procedures above

On Fri, Nov 12, 2010 at 2:45 PM, Lim,  Raymond <rl2240@columbia.edu> wrote:

> I preserve before the loop in my actual code. The loop right now creates team 101 with 3 members, team 102 with 5 members, team 103 with 3 members, etc. Yes, there's a one-to-one mapping from tt to NN. I basically need two loop indices to change simultaneously. For example, first round (i=103, j=3), second round (i=139, j=5), third round (i=230, j=3). Of course, the real thing is a couple hundred pairs.
>
> -Raymond
>
> preserve
> local tt=100
> qui foreach NN of numlist 3 5 3 4 {
>       bsample `NN'
>       local tt=`tt'+1
>       replace team=`tt'
>       save simteam_`tt'.dta, replace
>       restore
>       preserve
>       }
>

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