Announcement

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

  • Draw a random integer from the interval (a,b) but not c

    Dear community,

    I am trying to draw a random integer from an interval (a,b) but not c.
    c obviously is inside the interval.

    Specifically, I have a group of 20 individuals, and I selected an individual (say individual 5).
    I need the function to randomly select a new individual in the group.

    Code:
    gen player = .
    replace player = 1 if individual_counter == 5
    
    replace player = 2 if individual_counter == runiformint(1,20) // and here I want to exclude the possibility of having 5 chosen

    Thank you!

  • #2
    Here is a program that will do just that. You specify -lower limit, upper limit, to exclude- in the syntax.

    Code:
    capture program drop select
    program define select, rclass
    args a b c val
    if `b'<=`a'{
        display as error "the upper limit must exceed the lower limit"
        exit
    }
    forval i=1/5{
        local val= runiformint(`1', `2')
        if `val'!=`3'{
            display "`val'"
            continue, break
        }
    }
    end
    
    *TEST1
    select 1 10 5
    
    *TEST2
    select 12 1 3
    Res.:

    Code:
    . *TEST1
    .
    . select 1 10 5
    6
     
    .
    . *TEST2
    
    .
    . select 12 1 3
    the upper limit must exceed the lower limit
    Last edited by Andrew Musau; 08 Sep 2023, 13:31.

    Comment


    • #3
      Here's another approach (probably less flexible) approach that looks like works for the specific situation described in #1.

      Code:
      clear
      set obs 20
      generate byte individual_counter = _n
      generate player = 1 if individual_counter==5
      set seed 230908 // Change the seed value if you like
      
      local ui = 5
      while `ui'==5 {
          local ui = floor((20-1+1)*runiform() + 1)
          display "ui = " `ui'
      }
      replace player = 2 if individual_counter==`ui'
      list if !missing(player), clean
      
      /* References
      
      https://blog.stata.com/2012/07/18/using-statas-random-number-generators-part-1/
      https://www.stata.com/manuals/pwhile.pdf#pwhile
      
      */
      Output:

      Code:
      . list if !missing(player), clean
      
             indivi~r   player  
        5.          5        1  
        9.          9        2
      --
      Bruce Weaver
      Email: [email protected]
      Version: Stata/MP 19.5 (Windows)

      Comment


      • #4
        Thank you

        Comment

        Working...
        X