Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract month and year from a zoo::yearmon object

Tags:

date

r

zoo

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

like image 260
adam.888 Avatar asked Oct 19 '22 08:10

adam.888


People also ask

How do you extract month and year from POSIXct in R?

For example, here's how to extract the year from a date: 1) date <- as. POSIXct("02/03/2014 10:41:00", format = "%m/%d/%Y %H:%M:%S) , and 2) format(date, format="%Y") . Now, you know how to use R to extract year from date.


2 Answers

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.

like image 148
Gavin Simpson Avatar answered Oct 21 '22 20:10

Gavin Simpson


The lubridate package is amazing for this kind of thing:

> require(lubridate)
> month(date1)
[1] 3
> year(date1)
[1] 2012
like image 105
Ari B. Friedman Avatar answered Oct 21 '22 20:10

Ari B. Friedman