将年月("yyyy-mm"格式)转换为日期吗?
我有一个像这样的数据集:
I have a dataset that looks like this:
Month count
2009-01 12
2009-02 310
2009-03 2379
2009-04 234
2009-05 14
2009-08 1
2009-09 34
2009-10 2386
我想绘制数据(月份为x值,计数为y值).由于数据中存在空白,因此我想将本月的信息转换为日期.我试过了:
I want to plot the data (months as x values and counts as y values). Since there are gaps in the data, I want to convert the Information for the Month into a date. I tried:
as.Date("2009-03", "%Y-%m")
但是它没有用.怎么了?似乎as.Date()也需要一天,并且无法为该天设置标准值吗?哪个功能可以解决我的问题?
But it did not work. Whats wrong? It seems that as.Date() requires also a day and is not able to set a standard value for the day? Which function solves my problem?
尝试一下. (在这里,我们使用text=Lines
来保持示例的独立性,但实际上,我们将其替换为文件名.)
Try this. (Here we use text=Lines
to keep the example self contained but in reality we would replace it with the file name.)
Lines <- "2009-01 12
2009-02 310
2009-03 2379
2009-04 234
2009-05 14
2009-08 1
2009-09 34
2009-10 2386"
library(zoo)
z <- read.zoo(text = Lines, FUN = as.yearmon)
plot(z)
此数据在X轴上不是很漂亮,但是如果您实际上有更多数据,可以这样做,或者您可以使用?plot.zoo
的示例部分中所示的精美X轴代码.
The X axis is not so pretty with this data but if you have more data in reality it might be ok or you can use the code for a fancy X axis shown in the examples section of ?plot.zoo
.
上面创建的动物园系列z
具有"yearmon"
时间索引,如下所示:
The zoo series, z
, that is created above has a "yearmon"
time index and looks like this:
> z
Jan 2009 Feb 2009 Mar 2009 Apr 2009 May 2009 Aug 2009 Sep 2009 Oct 2009
12 310 2379 234 14 1 34 2386
"yearmon"
也可以单独使用:
> as.yearmon("2000-03")
[1] "Mar 2000"
注意:
-
"yearmon"
类对象按日历顺序排序.
"yearmon"
class objects sort in calendar order.
这将以等距间隔绘制月度点,这可能是想要的;但是,如果希望以不相等的间隔绘制点,这些间隔与每个月中的天数成比例,则将z
的索引转换为"Date"
类:time(z) <- as.Date(time(z))
.
This will plot the monthly points at equally spaced intervals which is likely what is wanted; however, if it were desired to plot the points at unequally spaced intervals spaced in proportion to the number of days in each month then convert the index of z
to "Date"
class: time(z) <- as.Date(time(z))
.