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
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
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)
?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).
Feb 1, 2014 at 20: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>
td = as.Date('2000/01/01') - as.Date('1999/01/01')
as.Date('1999/01/01') + sample(0:td, 12)
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')