【发布时间】:2014-02-25 11:05:01
【问题描述】:
如何在特定日期范围内生成一组 12 个随机日期?
我认为以下方法会起作用:
sample(as.Date(1999/01/01), as.Date(2000/01/01),12)
但结果看起来像是一组随机数字?
谢谢
【问题讨论】:
如何在特定日期范围内生成一组 12 个随机日期?
我认为以下方法会起作用:
sample(as.Date(1999/01/01), as.Date(2000/01/01),12)
但结果看起来像是一组随机数字?
谢谢
【问题讨论】:
seq 有一个 Date 类的方法,它适用于此:
sample(seq(as.Date('1999/01/01'), as.Date('2000/01/01'), by="day"), 12)
【讨论】:
?format.Date。要生成这种格式,您需要格式字符串'%m/%d/%Y'(或者可能是'%d/%m/%Y'——因此我建议不要使用这种格式)。
几种方式:
从单个 Date 对象开始,然后添加来自 sample() 的结果
从Date 对象的序列开始,然后sample() 它。
这里是 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>
【讨论】:
td = as.Date('2000/01/01') - as.Date('1999/01/01')
as.Date('1999/01/01') + sample(0:td, 12)
【讨论】:
为了遵循rnorm、rnbinom、runif 等基本 R 函数,我在下面创建了函数 rdate 以根据 accepted answer of Matthew Lundberg 返回随机日期。
默认范围是当年的第一天和最后一天。
rdate <- function(x,
min = paste0(format(Sys.Date(), '%Y'), '-01-01'),
max = paste0(format(Sys.Date(), '%Y'), '-12-31'),
sort = TRUE) {
dates <- sample(seq(as.Date(min), as.Date(max), by = "day"), x, replace = TRUE)
if (sort == TRUE) {
sort(dates)
} else {
dates
}
}
正如预期的那样,它返回有效日期:
> class(rdate(12))
[1] "Date"
还有随机性检查,从今年开始生成一百万个日期:
> hist(rdate(1000000), breaks = 'months')
【讨论】: