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
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)
Several ways:
Start with a single Date
object, and just add result from sample()
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>
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')
td = as.Date('2000/01/01') - as.Date('1999/01/01')
as.Date('1999/01/01') + sample(0:td, 12)
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...