Announcement

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

  • Randomly selecting numbers from a list

    Hi,


    I am running a simulation where I generate a variable that takes on integer values 1-5 with equal probability using the command:
    gen initial = int(1+(5*uniform()))

    I then want to create a variable (secondary) that randomly selects one of the four numbers that is never one and is also not the value of the variable "initial"
    (ex. if initial==2, secondary can take on values 3,4, 5 with equal probability). Would this be achieve with something like:
    gen secondary= int(2+(4*uniform())) if true==1
    replace secondary=int(3+(4*uniform())) if true==2, etc?

    Thank you.

  • #2
    Code:
    //    CREATE DEMONSTRATION DATA SET
    clear
    set obs 10000
    set seed 1234
    gen initial = runiformint(1, 5)
    
    //     CREATE SECONDARY ACCORDING TO SPECIFICATIIONS
    gen secondary = runiformint(2, 5) if initial == 1
    replace secondary = runiformint(3, 5) if inlist(initial, 2, 3)
    replace secondary = 2 if initial == 3 & secondary == 3
    replace secondary = runiformint(2, 4) if inlist(initial, 4, 5)
    replace secondary = 5 if initial == 4& secondary == 4
    
    //    VERIFY SPECIFICATIONS ARE MET
    assert secondary != 1
    assert secondary != initial
    tab secondary initial, col
    I don't understand your reference to some variable "true" in the code above. I assume you meant "initial."

    My gut tells me that there is a simpler, shorter way to do this, but it isn't immediately obvious to me how, and this isn't too bad.

    Comment


    • #3
      This may be the simpler, short approach that Clyde was thinking of.
      Code:
      //     CREATE SECONDARY ACCORDING TO SPECIFICATIIONS
      gen secondary = runiformint(2, 4+(initial==1))
      replace secondary = secondary + (secondary>=initial & initial>1)

      Comment


      • #4
        William Lisowski Yes, thank you!

        Comment

        Working...
        X