Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Random Dates

Tags:

date

r

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

like image 386
AAA Avatar asked Feb 01 '14 19:02

AAA


People also ask

How do you generate random date?

To generate random dates between two dates, you can use the RANDBETWEEN function, together with the DATE function. This formula is then copied down from B5 to B11. The result is random dates between Jan 1, 2016 and Dec 31, 2016 (random dates in the year 2016).

How do I randomize date and time in Excel?

1. RAND()*(13-11)/24+11/24: This formula will return a random value in 24hr time format between 11 o'clock and 13 o'clock. 2. TEXT(RAND()*(15-11)/24+11/24, “HH:MM: SS”): This formula will return the values returned by the RAND function in standard HH: MM: SS format.


2 Answers

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) 
like image 174
Matthew Lundberg Avatar answered Oct 03 '22 03:10

Matthew Lundberg


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>  
like image 23
Dirk Eddelbuettel Avatar answered Oct 03 '22 04:10

Dirk Eddelbuettel