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

ada*_*888 112 r

我有一个yearmon对象:

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

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

month1 <- fn(date1)
year1 <- fn(date1)
Run Code Online (Sandbox Code Playgroud)

我应该用什么功能代替 fn()

Rei*_*son 143

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

date1 <- as.yearmon("Mar 2012", "%b %Y")
Run Code Online (Sandbox Code Playgroud)

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

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

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

> as.numeric(format(date1, "%m"))
[1] 3
> as.numeric(format(date1, "%Y"))
[1] 2012
Run Code Online (Sandbox Code Playgroud)

查看?yearmon?strftime了解详细信息 - 后者解释了您可以使用的占位符字符.

  • %B为整月,即3月"代替""3月" (4认同)

Ari*_*man 100

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

> require(lubridate)
> month(date1)
[1] 3
> year(date1)
[1] 2012
Run Code Online (Sandbox Code Playgroud)

  • 哈谢谢你的回答.当你想做像if(year(date1)> 2014){year(date1)< - year(date1) - 100}这样的事情时,它尤其胜过其他解决方案 (2认同)

Mat*_*ert 15

我知道OP正在zoo这里使用,但我发现这个帖子谷歌搜索ts同一问题的标准解决方案.所以我想我也会添加一个zoo免费答案ts.

# create an example Date 
date_1 <- as.Date("1990-01-01")
# extract year
as.numeric(format(date_1, "%Y"))
# extract month
as.numeric(format(date_1, "%m"))
Run Code Online (Sandbox Code Playgroud)


Jam*_*mes 12

你可以使用format:

library(zoo)
x <- as.yearmon(Sys.time())
format(x,"%b")
[1] "Mar"
format(x,"%Y")
[1] "2012"
Run Code Online (Sandbox Code Playgroud)


use*_*167 5

对于大型载体:

y = as.POSIXlt(date1)$year + 1900    # x$year : years since 1900
m = as.POSIXlt(date1)$mon + 1        # x$mon : 0–11
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案,因为 R 已经提供了方便的“POSIXlt”对象,使得动物园包不再需要 (2认同)