0

I don't know what I'm doing wrong with my date data. A sample of the Date column in the housing_data data frame are as follows:

"February 2012"  "March 2012"     "April 2012"     "May 2013"       "July 2015"      "March 2016"    
"May 2016"       "April 2017"     "July 2017"      "October 2017"   "December 2017"  "February 2018"

I run housing_data$Date <- base::as.Date(housing_data$Date, "%B %Y") and I get nothing but NA back as if I have the formatting incorrect. What am I missing?

Kyle Dixon
  • 285
  • 4
  • 13
  • A `Date` needs a day: [Converting year and month (“yyyy-mm” format) to a date?](https://stackoverflow.com/questions/6242955/converting-year-and-month-yyyy-mm-format-to-a-date). In addtion, `%B` is locale sensitive, which _may_ be an issue: [strptime, as.POSIXct and as.Date return unexpected NA](https://stackoverflow.com/questions/13726894/strptime-as-posixct-and-as-date-return-unexpected-na) – Henrik Sep 04 '20 at 18:14

1 Answers1

1

I would suggest adding a day value to your string in this way:

#Data
x1 <- c("February 2012", "March 2012", "April 2012", "May 2013", "July 2015")

Code:

#For date
as.Date(paste('01',x1),'%d %B %Y')

Output:

[1] "2012-02-01" "2012-03-01" "2012-04-01" "2013-05-01" "2015-07-01"

Or you can try:

#Format date
format(as.Date(paste('01',x1),'%d %B %Y'),'%B %Y')

Output:

[1] "February 2012" "March 2012"    "April 2012"    "May 2013"      "July 2015" 
Duck
  • 39,058
  • 13
  • 42
  • 84
  • Ah you're a genius. Is this true any time you don't have a full month, day, year combo? – Kyle Dixon Sep 04 '20 at 18:17
  • 1
    @KyleDixon Yes you can use that trick in order to format your dates. I hope this was useful for you :) – Duck Sep 04 '20 at 18:18
  • @KyleDixon If you think this answer was helpful, you could accept it by clicking the tick on the left side of this answer. – Duck Sep 04 '20 at 18:28
  • 1
    @KyleDixon, to answer your question. Yes a valid date has a day, month and year. If the day is not specified then it is not a valid date and any attempt to convert to Date object will fail. – Dave2e Sep 04 '20 at 18:50