Convert integer to class Date

我的梦境 提交于 2020-07-24 09:15:03

问题


I have an integer which I want to convert to class Date. I assume I first need to convert it to a string, but how?

My attempt:

v <- 20081101
date <- as.Date(v, format("%Y%m%d"))

Error in charToDate(x) : character string is not in a standard unambiguous format

Using paste() works, but is that really the correct way to do the conversion?

date <- as.Date(paste(v), format("%Y%m%d"))
date
[1] "2008-11-01"

class(date)
# [1] "Date"

回答1:


as.character() would be the general way rather than use paste() for its side effect

> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"

(I presume this is a simple example and something like this:

v <- "20081101"

isn't possible?)




回答2:


Another way to get the same result:

date <- strptime(v,format="%Y%m%d")



回答3:


You can use ymd from lubridate

lubridate::ymd(v)
#[1] "2008-11-01"

Or anytime::anydate

anytime::anydate(v)
#[1] "2008-11-01"


来源:https://stackoverflow.com/questions/4104359/convert-integer-to-class-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!