Announcement

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

  • binary random variable generator

    Hi all

    I want to generate binary random sample with the mean 0.3.
    I think that runiformint(0,1) might help me but the mean is 0.5.

    I don't know how to do it. Please help!
    Thank you



  • #2
    Code:
    gen wanted = runiform() < 0.3

    Comment


    • #3
      Thank you Nick. It helps me.

      Comment


      • #4
        Also see: M. Buis (2007) Stata Tip 48: Discrete uses for uniform(). The Stata Journal, 7(3): 434-435.
        http://www.stata-journal.com/article...article=pr0032

        Note that at the time that that Stata tip was written runiform() was called uniform(). So whenever you see uniform() in that article, you need to write runiform()
        ---------------------------------
        Maarten L. Buis
        University of Konstanz
        Department of history and sociology
        box 40
        78457 Konstanz
        Germany
        http://www.maartenbuis.nl
        ---------------------------------

        Comment


        • #5
          Thank you, Maarten. It is really helpful.

          Comment


          • #6
            The above code does not assure that the mean of wanted will be 0.3, which of course will only be possible for specific numbers of observations in the dataset.

            Code:
            sysuse auto.dta
            gen wanted = runiform() < 0.3
            sum wanted
            However, I think this code gives a better approximation than the first version

            Code:
            set seed 2803
            gen random = runiform()
            sort random
            local cut = round((_N / 10) * 3)
            gen wanted2 = _n <= `cut'
            sum wanted2
            Last edited by Felix Stips; 07 Jan 2021, 02:47.

            Comment


            • #7
              It depends on what you want. If you want to get a mean that every time you run it is as close to .3 as possible, then what Felix Stips proposes is an idea. However, if you want to get a set of draws from a bernouilie distribution, then what I propose is the right thing.
              ---------------------------------
              Maarten L. Buis
              University of Konstanz
              Department of history and sociology
              box 40
              78457 Konstanz
              Germany
              http://www.maartenbuis.nl
              ---------------------------------

              Comment

              Working...
              X