Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

r - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...