Unable to convert Month-Year string to Date in R

I'm using as.Date to convert a string like Aug-2002 to a dates object representing just the month of Aug of 2002, or if a day must be specified, Aug 1, 2002.

However

> as.Date(c('07-2002'), "%M-%Y")
[1] "2002-11-06"

> as.Date(c('Aug-2002'), "%b-%Y")
[1] NA

Why does the first line of code convert it to a different month and day? And the second one is NA?

I referred to this table for the formatting symbols.

enter image description here


Solution 1:

The problem you are having is that the dates you have do not have a day value. Without the day value the format="%m-%Y" will not work in as.Date. These options below will solve them:

as.Date(paste0('01-', c('07-2002')), format="%d-%m-%Y")

library(zoo) #this is a little more forgiving:
as.yearmon(c('07-2002'), "%m-%Y")
as.yearmon(c('Aug-2002'), "%b-%Y")

as.Date(as.yearmon(c('07-2002'), "%m-%Y"))