我有一个yearmon
对象:
require(zoo)
date1 <- as.yearmon("Mar 2012", "%b %Y")
class(date1)
# [1] "yearmon"
我如何从中提取月份和年份?
month1 <- fn(date1)
year1 <- fn(date1)
我应该用什么函数来代替fn()
发布于 2012-03-17 19:35:34
对类"yearmon"
的对象使用format()
方法。这是您的示例日期(正确创建!)
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
-后者解释了可以使用的占位符字符。
发布于 2012-03-17 20:31:49
对于这类事情,lubridate package非常棒:
> require(lubridate)
> month(date1)
[1] 3
> year(date1)
[1] 2012
发布于 2014-09-04 18:08:08
我知道这里的OP使用的是zoo
,但我发现这个线程正在搜索解决相同问题的标准ts
解决方案。所以我想我也应该为ts
添加一个zoo
-free回答。
# 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"))
https://stackoverflow.com/questions/9749598
复制相似问题