ATMA
ATMA

Reputation: 1468

Generating a date from a string with a 'Month-Year' format

I have the following date and it's in a 'month-year' format. However, to plot the dates on the x-axis of a ggplot2 graphic, I'm trying to convert them into a date format. With the as.Date function, it produces NA values because no 'day' value is provided. So beyond pasting the day into each date using the paste() function, how can I handle adjusting the dates so that I can plot them.

date = c("Jan-10","Feb-10","Mar-10","Jun-10","Jul-10")
date

date = as.Date(date, "%m/%d/%Y")   # doesn't work
date = as.Date(as.yearmon(date, format="%y-%b"))  # doesn't work

Thanks!

Upvotes: 3

Views: 499

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

You've got it backwards:

library(zoo)
as.yearmon(date, format="%b-%y")
# [1] "Jan 2010" "Feb 2010" "Mar 2010" "Jun 2010" "Jul 2010"

Specify the format in the order in which it appears in the input.


Do not just arbitrarily specify the date format. Note what your attempts were looking for:

  • "%m/%d/%Y" does not work because that is expecting dates in the form of "10/31/2013"
  • "%y-%b" does not work because that is expecting dates in the form of "13-Oct"

Upvotes: 6

Related Questions