Announcement

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

  • Generating random numbers specific to different observations

    I currently have data that looks like the following:


    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float(IndividualNumber Flag)
    1 1
    1 0
    1 0
    1 0
    2 1
    2 0
    2 0
    2 0
    3 1
    3 0
    3 0
    4 1
    4 0
    4 0
    4 0
    end

    wherein the IndividualNumber variable signifies ID of the individual. The above data is a subset of a bigger dataset, details of which are not really relevant for this question. Individuals are observed over several years. I wish to create a random variable drawn from a standard normal distribution specific to each individual over all years. In order to do this, I have first created a flag variable called Flag. I have used the putmata command to input these 2 vectors into Mata.

    On Mata, I type the following code:

    Code:
    
    mata: D=J(rows(IndividualNumber), 1,0)
    
    mata: for (Flag==1) {
    matrix D[`i',1]=rnormal(1,1,0,1)
    
    }
    I am sure the code is horrendously wrong. I have first created a vector of zeroes, D. I wish to then replace elements of this vector by drawing from the standard normal distribution when the variable Flag takes on a value of 1. Any help is much apppreciated!




  • #2
    Code:
    mata:
    
    for (i=1;i<=rows(D);i++) {
          
           if (Flag[i,1]) D[i,1] = rnormal(1,1,0,1)
    
    }
    
    end

    Comment


    • #3
      Thanks a lot! Really appreciate it.

      Comment

      Working...
      X