Convert integer to class Date

RDateR Faq

R Problem Overview


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"

R Solutions


Solution 1 - R

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?)

Solution 2 - R

Another way to get the same result:

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

Solution 3 - R

You can use ymd from lubridate

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

Or anytime::anydate

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionElzo ValugiView Question on Stackoverflow
Solution 1 - RGavin SimpsonView Answer on Stackoverflow
Solution 2 - RViviView Answer on Stackoverflow
Solution 3 - RRonak ShahView Answer on Stackoverflow