Announcement

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

  • Create new variable with 1000 observations from random normal distributions

    As the title says, I'm having a hard time creating a new variable that is comprised of a list of means pulled from random normal distributions. For example, I want variable(x) to have 1000 observations. Each observation is the mean value from a randomly generated normal distribution. Variable(x1) would be 1000 observations with the SD for each randomly generated normal distribution. So, observation 1 would be the mean and SD from a randomly generated normal distribution, observation 2 would be the mean and SD from another randomly generated normal distribution, and so on.

    Using drawnorm I can generate an individual distribution and extract the distribution's mean and SD. I'm looking to automate the process so I don't have to run drawnorm 1,000 times and pull the mean/SD 1,000 times to generate the new variable.

    I've tried a for loop to try and automate the process, but I am having a hard time getting anything to work. Any advice is very much appreciated!!

    Hunter-

  • #2
    Code:
    clear
    set seed 1000
    quietly{
        forvalues x = 1/1000{
            drawnorm randvar`x',n(1000)
            sum randvar`x'
            local mean`x' `=r(mean)'
            local sd`x' `=r(sd)'
        }
        gen mean = .
        gen sd = .
        forvalues x = 1/1000{
            replace mean = `mean`x'' in `x'
            replace sd = `sd`x'' in `x'
        }
        drop randvar*
    }
    Last edited by Ali Atia; 11 Feb 2021, 15:23.

    Comment


    • #3
      Hunter:
      welcome to this forum.
      Another possible approach (built on a code that Brian Poi provided me with some years ago. Thanks once more, Brian!) is the following one (any mistake is obviously my own fault):
      Code:
      drop _all
      set obs 1000
      set seed 1
      g double mean_wanted=.
      g double sd_wanted=.
      quietly forvalues i = 1/1000 {
      preserve
      drawnorm wanted, n(1000)
      summ wanted
      scalar wanted_m = r(mean)
      scalar wanted_sd = r(sd)
      restore
      replace mean_wanted = wanted_m in `i'
      replace sd_wanted = wanted_sd in `i'
      }
      su mean_wanted
      su sd_wanted
      Kind regards,
      Carlo
      (Stata 19.0)

      Comment


      • #4
        Ali and Carlo, thank you so much for taking the time to respond to my question! I didn't realize I had gotten any responses, so I apologize for the slow response. I will give both of these a try as soon as I can.

        Best,
        Hunter-

        Comment

        Working...
        X