Rumi
Rumi

Reputation: 196

as.Date keeps returning NA - Mont-Year format

I imported csv data saved from excel and I am using a Mac if that matters.

To simplify things, I have been working with one particular entry from my data "Jan-12". This is of type character and in the form Month-Year.

This is what I have tried:

as.Date("Jan-12", format = "%b-%y")

I keep getting NA. I have browsed through other answers but haven't been able to figure out whats happening.

Upvotes: 0

Views: 94

Answers (2)

AndrewGB
AndrewGB

Reputation: 16856

Here is another option using zoo, then you can use as.Date.

library(zoo)

as.Date(as.yearmon("Jan-12", "%b-%y"))

# [1] "2012-01-01"

Upvotes: 2

Łukasz Deryło
Łukasz Deryło

Reputation: 1860

as.Date() help page says:

If the date string does not specify the date completely, the returned answer may be system-specific.

If you really need to use as.Date() you can append some fixed day (say 1st) to date and convert

mydate <- "Jan-12"
as.Date(paste0("01-", mydate), format= "%d-%b-%y")
"2012-01-01"

Or you can use lubridate::fast_strptime():

library(lubridate)
fast_strptime("Jan-12", "%b-%y")
"2012-01-01 UTC"

Upvotes: 2

Related Questions