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

查看:70
本文介绍了将年和月(“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 轴的代码/code> .

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" 类: 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"格式)转换为日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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