Zach
Zach

Reputation: 30331

Convert a month abbreviation to a numeric month, in R

I'm trying to write a function to convert 3-letter month abreviations to numeric values in R.

Here's what I have, I was wondering if there's a better way to do this:

numMonth <- function(x) {
    months <- list(jan=1,feb=2,mar=3,apr=4,may=5,jun=6,jul=7,aug=8,sep=9,oct=10,nov=11,dec=12)
    x <- tolower(x)
    sapply(x,function(x) months[[x]])
}

numMonth(c('JAN','DEC'))

Upvotes: 23

Views: 17566

Answers (2)

IRTFM
IRTFM

Reputation: 263481

Since month.abb is a system constant, why not use:

 match("jan", tolower(month.abb))
 # [1] 1

 mo2Num <- function(x) match(tolower(x), tolower(month.abb))
 mo2Num(c("jan", "JAN", "Feb", "junk")  )
 #[1]  1  1  2 NA

If you want to see the rest of the relatively small number of "system constants", go to

`?Constants`

The example text implies these should be in the language associated with your locale (although I'm not able to say with authority which of locales that would be. An alternate approach might have been to extract the month numbera after conversion to a POSIXlt-object. This approach requires remembering that the month number os 0-based, so you would need to add 1 in this instance.

Upvotes: 38

mbq
mbq

Reputation: 18638

Use vectorization, i.e.:

numMonth<-function(x) 
c(jan=1,feb=2,mar=3,apr=4,may=5,jun=6,jul=7,aug=8,sep=9,oct=10,nov=11,dec=12)[tolower(x)]

Upvotes: 6

Related Questions