Home > database >  as.Date keeps returning NA - Mont-Year format
as.Date keeps returning NA - Mont-Year format

Time:08-06

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.

CodePudding user response:

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"

CodePudding user response:

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"
  •  Tags:  
  • r
  • Related