[R] extracting month from date in numeric form

Gabor Grothendieck ggrothendieck at gmail.com
Tue Aug 21 18:17:19 CEST 2007

On 8/21/07, Gonçalo Ferraz <gferraz29 at gmail.com> wrote:
> Hi,
> Anyone knows what would be a short way of extracting a month from a date in
> numeric or integer format?
> months("1979-12-20")
> returns
> "December" in character format.
> How could I get 12 in numeric or integer format?

Here are a few solutions:

format(as.Date("1979-12-20"), "%m")

as.POSIXlt(as.Date("1979-12-20"))$mo + 1

as.numeric(substring("1979-12-20", 6, 7))

as.numeric(factor(months(as.Date("1979-12-20"), abbrev = TRUE), levels
= month.abb))

See R News 4/1 Help Desk article for more on dates.

More information about the R-help mailing list