Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good way to select random dates over a given interval using R?

Tags:

date

r

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?

like image 359
Neil Best Avatar asked Dec 06 '22 10:12

Neil Best


2 Answers

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.

like image 146
Gavin Simpson Avatar answered Jan 12 '23 17:01

Gavin Simpson


I'd use sample

dates <- Sys.Date() - 20:1
sample(dates)
like image 45
GSee Avatar answered Jan 12 '23 17:01

GSee