Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a month abbreviation to a numeric month, in R

Tags:

datetime

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'))
like image 812
Zach Avatar asked Aug 08 '11 19:08

Zach


People also ask

WHAT IS month ABB R?

abb in R. The month. abb is the three-letter abbreviations for the English month names. Sometimes date vector for months is recorded in numeric form, and it becomes difficult to treat or visualize it as a date vector.


2 Answers

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.

like image 120
IRTFM Avatar answered Sep 23 '22 13:09

IRTFM


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)] 
like image 41
mbq Avatar answered Sep 23 '22 13:09

mbq