使用as.Date格式化月份缩写 [英] Formatting month abbreviations using as.Date

查看:1296
本文介绍了使用as.Date格式化月份缩写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用月度数据,并且具有日期的字符向量格式:

  Sep / 2012 
Aug / 2012
七月/ 2012

等等,回到1981年。 ve尝试使用

  as.Date(dates,%b /%Y)

其中%b 表示月份缩写,但这只能返回NAs。注意:我已经找到一个解决方法,使用 gsub()来添加01 / 在每个条目前,如下所示:

  01 / Sep / 2012 
01 / Aug / 2012
01 / Jul / 2012

然后 as.Dates() code>工作,但这似乎有点偏执,并且不是严格准确。

解决方案

你在看对于动物园包中的 as.yearmon()根据您的日期

 日期<  -  c(2012年9月,2012年8月,2012年7月 )

我们加载包并转换为yearmon class

  require(zoo)
dates1< - as.yearmon(dates,format = %b /%Y)
dates1

哪些给了

  R> dates1 
[1]2012年9月2012年8月2012年7月

可以使用 as.Date()方法

$ b来强制类别Date
$ b

  R> as.Date(dates1)
[1]2012-09-012012-08-012012-07-01

这将是通过 gsub()获取您所做的一件更简单的方法。有一个 frac 参数,它控制了每天零件应该有多远:

 code> R> as.Date(dates1,frac = 0.5)
[1]2012-09-152012-08-162012-07-16
/ pre>

但这可能对你来说是足够的。



如果你真的只想把日期存储为你有他们,那么他们不是真正的日期,但如果你很高兴在动物园包中工作,那么yearmon类可以是用作 zoo 对象的索引,该对象是一个时间序列。


I'm working with monthly data and have a character vector of dates, formatted:

Sep/2012
Aug/2012
Jul/2012

and so on, back to 1981. I've tried using

as.Date(dates, "%b/%Y")

where %b represents month abbreviations, but this only returns NAs. What am I doing wrong?

Note: I already found a workaround using gsub() to add "01/" in front of each entry, like so:

01/Sep/2012
01/Aug/2012
01/Jul/2012

Then as.Dates() works, but this seems a little inelegant, and isn't strictly accurate anyway.

解决方案

You are looking for as.yearmon() in the zoo package. Given your dates

dates <- c("Sep/2012","Aug/2012","Jul/2012")

we load the package and convert to the "yearmon" class

require(zoo)
dates1 <- as.yearmon(dates, format = "%b/%Y")
dates1

Which gives

R> dates1
[1] "Sep 2012" "Aug 2012" "Jul 2012"

You can coerce to an object of class "Date" using the as.Date() method

R> as.Date(dates1)
[1] "2012-09-01" "2012-08-01" "2012-07-01"

Which would be a simpler way of getting the thing you did via gsub(). There is a frac argument which controls how far through the month the day component should be:

R> as.Date(dates1, frac = 0.5)
[1] "2012-09-15" "2012-08-16" "2012-07-16"

But that may ont be sufficient for you.

If you really only want the dates stored as you have them, then they aren't really dates but if you are happy to work within the zoo package then the "yearmon" class can be used as an index for a zoo object which is a time series.

这篇关于使用as.Date格式化月份缩写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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