将实际日期转换为 R 中的整数值

Turning an actual date into an integer value in R

使用 R,我希望能够将格式为“2014-12-31”的日期转换为整数 20141231,以便创建序列号。

我的目标很简单,就是能够完成这个用户问题的 REVERSE (Turning an integer string date into an actual date)。

感谢提供的任何帮助。

只需以这种方式格式化日期,然后对结果调用 as.integer

R> as.integer(format(Sys.Date(), "%Y%m%d"))
[1] 20151008

如果您的日期不是日期,而是一个字符串:要么先将其转换为日期,要么在调用 as.integer.

之前删除 "-"
R> dateString <- "2014-12-31"
R> as.integer(format(as.Date(dateString), "%Y%m%d"))
[1] 20141231
R> as.integer(gsub("-", "", dateString))
[1] 20141231

或者如果您已经有角色日期:

a <- "2015-03-15"
as.integer(gsub(pattern = "-", replacement="", x = a))
#[1] 20150315