Announcement

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

  • Randomly generating dates

    Is there a good method for generating random (but valid) dates in Stata?

    Gareth

  • #2
    Stata dates are just integers counting days from jan 1, 1960.
    So you need to identify the range of possible dates and figure out what numbers those dates correspond to. Then see help runiform for info on generating random numbers in a set range.
    For display purposes you'll likely want to format the resulting variables as a daily date. (%td)

    Comment


    • #3
      Yes. All dates are just integers in some units. That they appear as dates is just a matter of display format.

      I am guessing that you mean random sampling from a uniform distribution. Then what you want is some variant on

      a + floor(b * runiform))

      or

      (a - 1) + ceil(b * runiform())

      where floor() or ceil() secures integer output and the constants a and b give you the right range.

      Comment


      • #4
        Here's some example code to demonstrate what Sarah and Nick have said (but I used round() instead of floor() or ceil()).

        Code:
        args beg end
        
        local d1 = date("`beg'", "MDY")
        local d2 = date("`end'", "MDY")
        
        local n1 = min(`d1', `d2')
        local n2 = max(`d1', `d2')
        
        local rdate = `n1' + round(runiform() * (`n2' - `n1'))
        
        noi di %td `rdate'

        If that code is put in rdate.do, you can run it like
        Code:
        . run rdate "1/15/2008" "1/15/2010"
        29may2009
        . run rdate "1/15/2008" "1/15/2010"
        03apr2008
        . run rdate "1/15/2008" "1/15/2010"
        11apr2009

        Comment


        • #5
          I'm pretty sure you should use floor() or ceil() instead of round(), contrary to my example.

          Comment


          • #6
            Originally posted by Gareth View Post
            Is there a good method for generating random (but valid) dates in Stata?
            I would also suggest that you have a look at this discussion available through old Statalist.
            Kind regards,
            Konrad
            Version: Stata/IC 13.1

            Comment

            Working...
            X