简体   繁体   English

从“月/年”格式的字符串中生成日期

[英]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. 但是,要在ggplot2图形的x轴上绘制日期,我试图将它们转换为日期格式。 With the as.Date function, it produces NA values because no 'day' value is provided. 使用as.Date函数时,由于不提供“ day”值,因此会产生NA值。 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. 因此,除了使用paste()函数将日期粘贴到每个日期中之外,如何处理日期,以便可以绘制日期。

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

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" "%m/%d/%Y"无效,因为该日期预计为“ 10/31/2013”
  • "%y-%b" does not work because that is expecting dates in the form of "13-Oct" "%y-%b"无效,因为该日期以“ 13-Oct”形式出现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM