简体   繁体   English

如何在R中两个时间点之间创建随机日期向量?

[英]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: 在我看来,像在生成随机日期中一样使用sampleseq函数似乎更直接:

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: 如果我们正在使用POSIXct类,并且希望随机化小时,分钟和秒,而不仅仅是日期:

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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