51

How can I generate a set of 12 random dates within a specific date range?

I thought the following would work:

 sample(as.Date(1999/01/01), as.Date(2000/01/01),12)

But the result looks like a random set of numbers?

Thank you

AAA
  • 2,388
  • 9
  • 32
  • 47

5 Answers5

84

seq has a method for class Date which works for this:

sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 12)
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
  • How can I then change the format of the output to be in a format such as 01/01/1999? – AAA Feb 01 '14 at 19:39
  • 2
    See `?format.Date`. To produce this format, you want the format string `'%m/%d/%Y'` (or perhaps `'%d/%m/%Y'` -- for this reason I recommend against this format). – Matthew Lundberg Feb 01 '14 at 20:12
12

Several ways:

  1. Start with a single Date object, and just add result from sample()

  2. Start with a sequence of Date objects, and sample() it.

Here is 1:

R> set.seed(42)   
R> res <- Sys.Date() + sort(sample(1:10, 3))
R> res
[1] "2014-02-04" "2014-02-10" "2014-02-11"
R> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
5

To follow base R functions like rnorm, rnbinom, runif and others, I created the function rdate below to return random dates based on the accepted answer of Matthew Lundberg.

The default range is the first and last day of the current year.

rdate <- function(x,
                  min = paste0(format(Sys.Date(), '%Y'), '-01-01'),
                  max = paste0(format(Sys.Date(), '%Y'), '-12-31'),
                  sort = TRUE) {

  dates <- sample(seq(as.Date(min), as.Date(max), by = "day"), x, replace = TRUE)
  if (sort == TRUE) {
    sort(dates)
  } else {
    dates
  }

}

As expected, it returns valid dates:

> class(rdate(12))
[1] "Date"

And the randomness check, generating a million dates from this year:

> hist(rdate(1000000), breaks = 'months')

Histogram of rdate

MS Berends
  • 4,489
  • 1
  • 40
  • 53
3
td = as.Date('2000/01/01') - as.Date('1999/01/01')
as.Date('1999/01/01') + sample(0:td, 12)
Yuriy Kovalev
  • 639
  • 5
  • 9
0
generateRandomDate <- function(start_date, end_date) {
  random_days <- sample(0:(as.numeric(end_date - start_date)), 1)
  start_date + days(random_days)
}

> set.seed(0); sapply(1:12, function(x) generateRandomDate(ymd("2023-01-01"), ymd("2023-1-31")) ) %>% as.Date(origin = "1970-01-01")

[1] "2023-01-14" "2023-01-25" "2023-01-04" "2023-01-07" "2023-01-01" "2023-01-02" "2023-01-29" "2023-01-23" "2023-01-11" "2023-01-14" "2023-01-18" "2023-01-27"

Note the use of as.Date() and origin parameter. Not sure why the code wont run without them...

IVIM
  • 2,167
  • 1
  • 15
  • 41