Extract month and year from a zoo::yearmon object
I have a yearmon
object:
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)
What function should I use in place of fn()
Solution 1:
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"
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
See ?yearmon
and ?strftime
for details - the latter explains the placeholder characters you can use.
Solution 2:
The lubridate package is amazing for this kind of thing:
> require(lubridate)
> month(date1)
[1] 3
> year(date1)
[1] 2012
Solution 3:
I know the OP is using zoo
here, but I found this thread googling for a standard ts
solution for the same problem. So I thought I'd add a zoo
-free answer for ts
as well.
# 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"))