Announcement

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

  • How to generate random numbers within a specified range of values?

    Dear all,

    I want to generate a variable that contains random values within a specified range (e.g., 600 to 1201) and I also need to specify the conditional if to be able to generate those values only for a particular group of observations that meet certain criteria.

    I tried the following but it didn“t work. Any help would be very much appreciated.

    gen double u = (1201-600)*runiform() + 1 if ctrycode==1 & income_decile==1

    Best,
    Barbara
    Last edited by Barbara Zarate; 15 Oct 2015, 11:39.

  • #2
    Didn't work? Didn't it work at all, or did it give an unexpected result? Please tell what "didn't work" means.
    Apart from that: If you want a range 600-1201, it is:
    Code:
    gen u = 600 + 601*runiform()

    Comment


    • #3
      Svend gives very good advice.

      In addition, the help shows that in Stata 14 there is a different form runiform(a,b), so either you didn't read the help (http://www.statalist.org/forums/help#before) or you forgot to tell us that you are using a previous version (http://www.statalist.org/forums/help#version)

      Comment


      • #4
        Thank you, Svend. Let me be more specific. I received an error message stating that "(12001-600)" was not a valid name.

        I just followed your code and it worked perfectly.

        Thank you very much.

        Comment


        • #5
          I can't reproduce that error:

          Code:
          . set obs 1
          obs was 0, now 1
          
          . gen double u = (1201-600)*runiform()
          
          . gen double u2 = (12001-600)*runiform()
          I would check for letters i, I, o, O in error for 0, 1.

          Comment


          • #6
            Thank you, Nick. I will do so next time. And yes, I am using Stata 14 and I did look for help using "help runiform" and I also had a look at other websites which explain the use of commands for generating random numbers but I did not find / understood how to go about my specific question.

            Thanks again.

            Best,
            Barbara

            Comment


            • #7
              Thanks for the confirmation. It would seem to follow that StataCorp should add a few more examples to make this clearer.

              Comment

              Working...
              X