将年和月(“yyyy-mm”格式)转换为R? [英] Converting year and month ("yyyy-mm" format) to a date in R?

查看:105
本文介绍了将年和月(“yyyy-mm”格式)转换为R?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据集,如下所示:

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轴不是很漂亮的这个数据,但是如果你有更多的数据在现实中可能是可以的,或者您可以使用代码为一个花哨的X轴显示在示例部分?plot.zoo

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"

注意


  1. yearmon类对象以日历顺序排列。

  1. "yearmon" class objects sort in calendar order.

这将以等间隔的间隔绘制每个点,这可能是想要的;然而,如果希望以与每个月的天数成比例的间隔间隔不等间隔绘制点,则将 z 的索引转换为Date class: 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)) .

这篇关于将年和月(“yyyy-mm”格式)转换为R?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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