[r] 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()

This question is related to r date zoo

The answer is


Having had a similar problem with data from 1800 to now, this worked for me:

data2$date=as.character(data2$date) 
lct <- Sys.getlocale("LC_TIME"); 
Sys.setlocale("LC_TIME","C")
data2$date<- as.Date(data2$date, format = "%Y %m %d") # and it works

The question did not state precisely what output is expected but assuming that for month you want the month number (January = 1) and for the year you want the numeric 4 digit year then assuming that we have just run the code in the question:

cycle(date1)
## [1] 3
as.integer(date1)
## [1] 2012

The lubridate package is amazing for this kind of thing:

> require(lubridate)
> month(date1)
[1] 3
> year(date1)
[1] 2012

You can use format:

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

For large vectors:

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

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"))