0 votes
1 view
in R Programming by (5.3k points)

I have a yearmon object:


date1 <- as.yearmon("Mar 2012", "%b %Y")


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

1 Answer

0 votes
by (25.4k points)

To extract month and year from a yearmon object, you can use the format function from the base package as follows:



myDate <- as.yearmon("Apr 2005", "%b %Y")

> format(myDate, "%b")

[1] "Apr" #Month as character

> format(myDate, "%Y") 

[1] "2005" #Year as character

> format(myDate, "%m") 

[1] "04" #numeric month as character

> format(myDate, "%B")

[1] "April" #Full month name as character

To convert the output to a numeric type:

>as.numeric(format(myDate, "%m"))

[1] 4

> as.numeric(format(myDate, "%Y"))

[1] 2005


Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !