如何在data.table中使用lubridate来操作日期?

fumotvh3  于 2023-01-18  发布在  其他
关注(0)|答案(2)|浏览(129)

如何使用data.table和lubridate包来达到预期的结果(创建一个新的日期列,它是另一个日期列的函数)?
下面是一些简单的代码,但不起作用:

library(data.table); library(lubridate);
dt <- data.table(date=ymd( paste0("2022-01-", 1:5) ) ); dt 
         date
       <Date>
1: 2022-01-01
2: 2022-01-02
3: 2022-01-03
4: 2022-01-04
5: 2022-01-05

dt[, `Report date` := ymd(year(date)-5, month(date), day(date))]

Error in `[.data.table`(dt, , `:=`(`Report date`, ymd(year(date) - 5,  : 
  Supplied 15 items to be assigned to 5 items of column 'Report date'. If you wish to 'recycle' the RHS please use rep() to make this intent clear to readers of your code.
In addition: Warning message:
All formats failed to parse. No formats found.

谢谢!

polkgigr

polkgigr1#

另一种选择可以是:

dt[, `Report date` := date - years(5)]
dt
         date Report date
       <Date>      <Date>
1: 2022-01-01  2017-01-01
2: 2022-01-02  2017-01-02
3: 2022-01-03  2017-01-03
4: 2022-01-04  2017-01-04
5: 2022-01-05  2017-01-05
lbsnaicq

lbsnaicq2#

ymd需要单个字符串而不是3个部分,我们可能需要简单地使用paste

library(data.table)
library(lubridate)
dt[, `Report date` := ymd(paste(year(date)-5, month(date), day(date)))]

或者也可以使用ISOdate代替ymdISOdate可以接受多个参数以合并为datetime

dt[, `Report date2` := as.IDate(ISOdate(year(date)-5, month(date), day(date)))]
  • 输出
> dt
         date Report date Report date2
1: 2022-01-01  2017-01-01   2017-01-01
2: 2022-01-02  2017-01-02   2017-01-02
3: 2022-01-03  2017-01-03   2017-01-03
4: 2022-01-04  2017-01-04   2017-01-04
5: 2022-01-05  2017-01-05   2017-01-05

相关问题