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'))
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.
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.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With