我有一个包含许多列的数据集,其中一列是年份。对于每一行,我想随机生成一个日期,使其属于该行中的年份。
library(data.table)
claims <- data.table(claimAmount = runif(n = 10, min = 0, max = 200),
claimYear = sample(x = 2014:2019, size = 10, replace = TRUE))
我知道有人发布了这个函数作为解决方案:
rdate <- function(x,
min = paste0(format(claims$claimYear, '%Y'), '-01-01'),
max = paste0(format(claims$claimYear, '%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
}
}
并尝试将其应用于数据,但收到“无效的修剪参数”错误:
apply(claims, 1, rdate)
Error in prettyNum(.Internal(format(x, trim, digits, nsmall, width, 3L, :
invalid 'trim' argument
如何在 R 中轻松生成随机日期?
最佳答案
使用lubridate::days
:
as.POSIXct(paste0(claims$claimYear, "-01-01")) +
lubridate::days(sample(0:364, nrow(claims), TRUE))
[1] "2018-11-15 GMT" "2019-09-02 GMT" "2016-08-02 GMT" "2018-08-02 GMT"
[5] "2016-01-09 GMT" "2015-07-05 GMT" "2016-12-19 GMT" "2019-03-04 GMT"
[9] "2014-01-06 GMT" "2018-06-17 GMT"
关于r - 生成给定年份的随机日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63562954/