Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Help with Program that Draws Observations from Distribution and Nested Loop

    Dear all,

    I am using Stata 16, on mac. I was wondering how would I write a program that selects a particular number of observations from a specified distribution such as uniform, poisson, beta? Also how would I write a nested loop if I wanted to draw a sample mean from the 3 distributions I mentioned previously with sample sizes of 3, 50 ,500 ,and 10000 and replicate 500 times and plot a histogram of the resulting distributions of the sample means?

    Thank you in advance for your help,

    Jason Browen

  • #2
    Here is one way of doing that. To make the graph you need the twby package, which you can install by typing in Stata ssc install twby

    Code:
    clear all
    set seed 123456789
    set scheme s1color
    
    program define sim, rclass
        preserve
        syntax, n(numlist >0 integer sort)
        drop _all
        local k : word count `n'
        set obs `: word `k' of `n''
        tempvar x1 x2 x3
        gen `x1' = runiform()
        gen `x2' = rpoisson(.5)
        gen `x3' = rbeta(.5,.5)
        forvalues which= 1/3 {
            foreach obs of local n {
                sum `x`which'' in 1/`obs', meanonly
                return scalar m`which'_`obs' = r(mean)
            }
        }
        restore
    end
    
    simulate ///
        munif20=r(m1_20) munif50=r(m1_50) munif500=r(m1_500)  ///
        mpois20=r(m2_20) mpois50=r(m2_50) mpois500=r(m2_500)  ///
        mbeta20=r(m3_20) mbeta50=r(m3_50) mbeta500=r(m3_500)  ///
        , reps(10000) : sim, n(20 50 500)
    
    gen id = _n
    reshape long munif mpois mbeta, i(id) j(size)
    reshape long m, i(id size) j(dist) string
    label var dist "distribution"
    label var size "number of observations"
    
    *ssc install twby
    twby size dist, compact: twoway hist m
    Click image for larger version

Name:	Graph.png
Views:	1
Size:	69.5 KB
ID:	1524753

    Last edited by Maarten Buis; 15 Nov 2019, 01:49.
    ---------------------------------
    Maarten L. Buis
    University of Konstanz
    Department of history and sociology
    box 40
    78457 Konstanz
    Germany
    http://www.maartenbuis.nl
    ---------------------------------

    Comment

    Working...
    X