【问题标题】:using sapply on a vector of dates在日期向量上使用 sapply
【发布时间】:2019-11-14 13:56:17
【问题描述】:

我有一个向日期添加随机整数的函数:

rand_to_date = function(date){
newdate = as.Date(date) + sample(1:30, 1)
return(as.Date(newdate))
}

效果很好。但是,如果我尝试使用 sapply 将此函数应用于日期向量,例如

test_dates = c('2001-01-01', '2002-02-02', '2003-03-03', '2004-04-04')

sapply 不会返回日期格式的输出向量:

 sapply(test_dates,rand_to_date)
 2001-01-01 2002-02-02 2003-03-03 2004-04-04 
 11329      11748      12115      12513

相比之下, lapply 将返回日期列表。但是,再次将 unlist 应用于此输出会为我提供一个数字向量而不是日期。也没有

sapply(sapply(test,rand_to_date), as.Date)

工作。对我来说,将这些随机日期的向量作为输出的最简单方法是什么?

【问题讨论】:

  • as.Date(test_dates) + sample(1:30, length(test_dates), replace = TRUE)

标签: r


【解决方案1】:

1)由于c.Date方法的存在,先使用lapply再使用c。我们还简化了rand_to_date 并添加了set.seed 以使其可重现:

rand_to_date <- function(date) as.Date(date) + sample(30, 1)

set.seed(123)
test_dates <- c('2001-01-01', '2002-02-02', '2003-03-03', '2004-04-04')

do.call("c", lapply(test_dates, rand_to_date))
## [1] "2001-01-10" "2002-02-26" "2003-03-16" "2004-05-01"

2) 或者,我们可以像这样使 rand_to_date 向量化:

rand_to_date <- function(date) as.Date(date) + sample(30, length(date), TRUE)

set.seed(123)
test_dates <- c('2001-01-01', '2002-02-02', '2003-03-03', '2004-04-04')
rand_to_date(test_dates)
## [1] "2001-01-10" "2002-02-26" "2003-03-16" "2004-05-01"

【讨论】:

  • 有趣的是,我猜purrr 相当于reduce(map(test_dates, rand_to_date), c),它的价值。
  • invoke("c", map(test_dates, rand_to_date))
  • 谢谢,使用 do.call 似乎是最精简的解决方案。
【解决方案2】:

不幸的是sapply 丢弃了属性,包括 S3 类——这与你的功能无关; sapply(test_dates, as.Date) 以同样的方式失败。

您需要再次添加它们:

structure(sapply(test_dates,rand_to_date), 'Date')

【讨论】:

  • 我不知道 sapply 会删除类属性 - 我起初认为它是特定于日期作为变量类的东西。
【解决方案3】:

您可以将数字转换回日期。

as.Date(sapply(test_dates, rand_to_date), origin = "1970-01-01")

【讨论】:

    【解决方案4】:

    您可以在sapply 中使用as.character()

    sapply(test_dates,function(v) as.character(rand_to_date(v)),USE.NAMES = F)
    

    其中as.character(rand_to_date(v)) 将日期指定为character,而不是POSIXct 类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-29
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多