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

# Re: Fwd: st: Illustrate SRS in a graph

 From Maarten buis To statalist@hsphsun2.harvard.edu Subject Re: Fwd: st: Illustrate SRS in a graph Date Mon, 20 Sep 2010 07:49:29 +0000 (GMT)

```--- On Fri, 17/9/10, Richard Ohrvall wrote:
> Just an additional small question, is there some way that I can
> extract all the proportions and their lower and upper bonds
> from the simulation by using some sort of loop? I have made it by
> repeating the code for each group, i.e. [x:1], [x:2] and so on. But to
> make the code a bit leaner when I have many groups I assume there is some
> way to loop this, but my tries with -foreach var- did not work
> well. Any suggestions?

If you want lean code and accomodate many groups, you'll have to make
the loop work. Here is one example, it still contains a loop, only now
outside the simulation program.

*------------------- begin example --------------------
program drop _all
program define sim, eclass
// create population
drop _all
set obs 10000
gen x = cond(_n <=  500, 1, ///
cond(_n <= 5000, 2, 3))
// draw a 1% sample without replacement
sample 1
// estimate the proportions and return the results
proportion x
matrix b = e(b)
matrix V = e(V)
local df = `e(df_r)'
ereturn post b V
ereturn scalar df = `df'
end

// repeat this 20 times and store the results in a dataset
simulate _b _se df=e(df), reps(20) : sim

//graph the results
gen sample = _n
forvalues i = 1/3 {
gen lb_`i' = x_b_`i' - invttail(_eq2_df,0.025)*x_se_`i'
gen ub_`i' = x_b_`i' + invttail(_eq2_df,0.025)*x_se_`i'
}
twoway scatter sample x_b_1               || ///
scatter sample x_b_2               || ///
scatter sample x_b_3               || ///
rcap lb_1 ub_1 sample, horizontal  || ///
rcap lb_2 ub_2 sample, horizontal  || ///
rcap lb_3 ub_3 sample, horizontal  xline(.05 .45 .5)
*-------------------- end example --------------------------------

Hope this helps,
Maarten

--------------------------
Maarten L. Buis
Institut fuer Soziologie
Universitaet Tuebingen
Wilhelmstrasse 36
72074 Tuebingen
Germany

http://www.maartenbuis.nl
--------------------------

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