简体   繁体   中英

How do I create a vector of random dates between two time points in R?

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.

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"

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM