I have looked at this answer which lists all dates between time points. Ideally I would like to state start and end dates, and the number of elements I'd want in the vector, and get back random dates including replicates.
Asked
Active
Viewed 2,729 times
1
-
2use `seq` and standard `sample` function. – M-- Jul 28 '17 at 20:20
-
What @Masoud said and include `replace=TRUE` – ekstroem Jul 28 '17 at 20:24
-
2Possible duplicate of [Generating Random Dates](https://stackoverflow.com/questions/21502332/generating-random-dates) – M-- Jul 28 '17 at 20:25
2 Answers
5
start_date <- as.Date('2015-01-01')
end_date <- as.Date('2017-01-01')
set.seed(1984)
as.Date(sample( as.numeric(start_date): as.numeric(end_date), 10,
replace = T),
origin = '1970-01-01')
[1] "2016-04-27" "2015-11-16" "2015-10-01" "2015-08-31" "2016-06-23"
[6] "2016-09-23" "2015-01-24" "2015-11-24" "2016-08-30" "2015-06-07"

Mouad_Seridi
- 2,666
- 15
- 27
5
Using the sample
and seq
functions as in Generating Random Dates seems to me the more straight forward approach:
set.seed(1984)
sample(seq(as.Date('2015-01-01'), as.Date('2017-01-01'), by = "day"), 10)
Output:
[1] "2016-04-27" "2015-11-16" "2015-09-30" "2015-08-30" "2016-06-20"
[6] "2016-09-19" "2015-01-24" "2015-11-21" "2016-08-23" "2015-06-05"
If we are working with the class POSIXct and we'd like randomized hours, minutes, and seconds, not just dates:
set.seed(1984)
sample(seq(as.POSIXct('2015-01-01'), as.POSIXct('2017-01-01'), by = "sec"), 10)
Output:
[1] "2016-04-26 15:04:13 CEST" "2015-11-16 10:17:23 CET"
[3] "2015-09-30 22:50:41 CEST" "2015-08-30 23:17:49 CEST"
[5] "2016-06-23 04:49:01 CEST" "2016-09-22 14:37:58 CEST"
[7] "2015-01-24 17:04:13 CET" "2015-11-24 07:13:42 CET"
[9] "2016-08-29 16:13:13 CEST" "2015-06-06 21:29:18 CEST"

mpalanco
- 12,960
- 2
- 59
- 67