r - 生成给定年份的随机日期

标签 r date data.table

我有一个包含许多列的数据集,其中一列是年份。对于每一行,我想随机生成一个日期,使其属于该行中的年份。

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/

相关文章:

r - 如何将等值面夹到球上?

r - R中传单中的addMarkers?

R:海量数据帧的简单随机样本

javascript - 以下函数中加号 (+) 的作用是什么,该函数摘自 jquery 源代码

r - 存储和使用对于内存来说太大的数据帧的最佳实践?

java - 尝试使用日期方法时出现日期异常

linux - 如何在shell脚本中显示不同时区变量中存储的日期

r - data.table 默认外部连接与 setkey,计算行(列出键的频率)

r - data.table 在只有一行时添加列表作为列

r - 用 R data.table 填充缺失的行