从 zoo::yearmon 对象中提取月份和年份 [英] Extract month and year from a zoo::yearmon object

查看:29
本文介绍了从 zoo::yearmon 对象中提取月份和年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 yearmon 对象:

require(zoo)
date1 <- as.yearmon("Mar 2012", "%b %Y")
class(date1)
# [1] "yearmon"

如何从中提取月份和年份?

How can I extract the month and year from this?

month1 <- fn(date1)
year1 <- fn(date1)

我应该用什么函数代替fn()

推荐答案

"yearmon" 类的对象使用 format() 方法.这是您的示例日期(正确创建!)

Use the format() method for objects of class "yearmon". Here is your example date (properly created!)

date1 <- as.yearmon("Mar 2012", "%b %Y")

然后我们可以根据需要提取日期部分:

Then we can extract the date parts as required:

> format(date1, "%b") ## Month, char, abbreviated
[1] "Mar"
> format(date1, "%Y") ## Year with century
[1] "2012"
> format(date1, "%m") ## numeric month
[1] "03"

这些以字符形式返回.在适当的情况下,如果您希望年份或数字月份作为数字变量,请在 as.numeric() 中换行,例如

These are returned as characters. Where appropriate, wrap in as.numeric() if you want the year or numeric month as a numeric variable, e.g.

> as.numeric(format(date1, "%m"))
[1] 3
> as.numeric(format(date1, "%Y"))
[1] 2012

有关详细信息,请参阅 ?yearmon?strftime - 后者解释了您可以使用的占位符.

See ?yearmon and ?strftime for details - the latter explains the placeholder characters you can use.

这篇关于从 zoo::yearmon 对象中提取月份和年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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