使用'Month-Year'格式从字符串中生成日期 [英] Generating a date from a string with a 'Month-Year' format

查看:455
本文介绍了使用'Month-Year'格式从字符串中生成日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下日期,并且采用'月 - 年'格式。但是,要绘制ggplot2图形的x轴上的日期,我试图将它们转换为日期格式。使用as.Date函数,它会生成NA值,因为不提供日值。因此,除了使用paste()函数将日期粘贴到每个日期之外,我如何处理调整日期以便我可以绘制它们。

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

日期= as.Date(日期,%m /%d /%Y)#不起作用
日期= as.Date(as.yearmon(date,format =%y-%b))#不起作用

谢谢!

解决方案

您已经得到了它:

  library(zoo)
as.yearmon(date,format =%b-%y)
#[1]Jan 2010 2010年2月2010年3月2010年6月2010年7月

订单出现在输入中。




不要只是任意指定日期格式。请注意您尝试查找的内容:




  • %m /%d /%Y不起作用,因为那是以10/31/2013​​形式出现的日期

  • %y-%b不起作用,因为那是以13-Oct形式出现的日期


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!

解决方案

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"

这篇关于使用'Month-Year'格式从字符串中生成日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆