3

I am trying to convert the following format to date:

as.Date('Mar.17', format = '%b.%y')

but it returns NA.

What am I missing?

Update, I am expecting to get March 2017, not 2018

2
  • 2
    It's not a date unless it has a month, day, and year. Apr 20, 2018 at 19:56
  • 1
    Could try: as.Date(paste0('Mar.17',1), format = '%b.%y%d')
    – Mike H.
    Apr 20, 2018 at 20:08

4 Answers 4

5

it should be:

as.Date('Mar.17', format = '%b.%d')
3
  • ... if it's the current year. Apr 20, 2018 at 19:59
  • Thank you, I wanted it to convert to March 1, 2017 Apr 20, 2018 at 19:59
  • 2
    you cannot expect R to understand that you want March 1st; so how about lubridate::dmy(paste(1, 'Mar.17') (I prefere lubridate functions for handing date variables)
    – jhvdz
    Apr 20, 2018 at 20:07
1

Assuming the 17 part is the year, you could use sub to add in a day number to make it an actual date.

as.Date(sub("\\.", "01", "Mar.17"), "%b%d%y")
# [1] "2017-03-01"
1

as.yearmon from zoo package will do the trick and provide date(Mar 2017) as expected by OP.

library(zoo)

as.yearmon("Mar.17", "%b.%y")
#[1] "Mar 2017"

Another option to convert it to 1 March 2017

as.Date(as.yearmon("Mar.17", "%b.%y"), frac = 0)
#[1] "2017-03-01"
1

You need the point for %b month format, at least in my computer

as.Date(paste0( "01",'mar.2017'), format = '%d%b%Y')

"2017-03-01"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.