I could not find a similar question so I thought it might be useful to someone else and/or generate some discussion. I wanted to sample some daily data randomly for a quick-and-dirty validation of some processing I had done. The question is, given an interval of start and end dates, how would one compute a vector of random dates over that interval?
One easy option is to generate the set of dates you want and then sample()
from them in the usual way:
Start <- as.Date("2013-01-01")
End <- as.Date("2013-01-31")
dates <- seq(from = Start, to = End, by = 1)
set.seed(1)
draw1 <- sample(dates, 5)
draw2 <- sample(dates, 5)
> draw1
[1] "2013-01-09" "2013-01-12" "2013-01-17" "2013-01-26"
[5] "2013-01-06"
> draw2
[1] "2013-01-28" "2013-01-29" "2013-01-20" "2013-01-18"
[5] "2013-01-02"
May not be the most efficient if the interval is long as you need to generate all the dates, but the code is quite clean and easy to grep the meaning of.
I'd use sample
dates <- Sys.Date() - 20:1
sample(dates)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With