Rprogrammer
Rprogrammer

Reputation: 477

Convert month's number to Month name

I need to convert this integer vector which contains the number of months in the year to month's name.

for example :

1
2
3

The expected result should be :

January
February
March

How can I do this, please? Thank you for your suggestions!

Upvotes: 8

Views: 18350

Answers (3)

Mark
Mark

Reputation: 12518

library(lubridate)

> month(1:3, label = TRUE, abbr = FALSE)
# [1] January  February March  
# 12 Levels: January < February < March < April < May < June < ... < December 

One advantage of this, over using month.name, is that it's given as an ordered factor, which can be useful if you're using data where months may be missing from the data, but important for when you go to plot it.

You're also able to change the locale (using the argument locale) if you want to get the months for a different place than the default of your R environment.

Upvotes: 0

Bernhard
Bernhard

Reputation: 4417

If predefined month.name does not work for your language or your special needs, just make a vector of names that is best for your work case like e.g.

my.month.name <- Vectorize(function(n) c("Januar", "Februar", "Maerz", 
                                         "April", "Mai", "Juni", "July", 
                                         "August", "September", "Oktober",
                                         "November", "Dezember")[n])

# examples
my.month.name(1)
my.month.name(2)
my.month.name(3:5)

This will work for other things than months as well.

Upvotes: 4

akrun
akrun

Reputation: 886938

We can just use month.name to change the index of months to its corresponding name

month.name[v1]

and there is also a 3 character abbreviation for month

month.abb[v1]

data

set.seed(24)
v1 <- sample(1:12, 24, replace = TRUE)

Upvotes: 16

Related Questions