为了账号安全,请及时绑定邮箱和手机立即绑定

从Zoo :: yearmon对象中提取月份和年份

从Zoo :: yearmon对象中提取月份和年份

哔哔one 2019-11-11 15:32:01
我有一个yearmon对象:require(zoo)date1 <- as.yearmon("Mar 2012", "%b %Y")class(date1)# [1] "yearmon"如何从中提取月份和年份?month1 <- fn(date1)year1 <- fn(date1)我应该用什么功能代替 fn()
查看完整描述

3 回答

?
喵喔喔

TA贡献1735条经验 获得超5个赞

将format()方法用于class对象"yearmon"。这是您的示例日期(正确创建!)


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

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


> 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()如果希望将年份或数字月份作为数字变量,请在适当的地方包装,例如


> as.numeric(format(date1, "%m"))

[1] 3

> as.numeric(format(date1, "%Y"))

[1] 2012

请参阅?yearmon和,?strftime以获取详细信息-后者解释了可以使用的占位符。


查看完整回答
反对 回复 2019-11-11
?
青春有我

TA贡献1784条经验 获得超8个赞

该lubridate包是令人惊叹的这种事情:


> require(lubridate)

> month(date1)

[1] 3

> year(date1)

[1] 2012


查看完整回答
反对 回复 2019-11-11
  • 3 回答
  • 0 关注
  • 1216 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信