10

I am using data that includes full month names:

months <- c("March",     "April",     "May",       "June",      "July",  "August",  "September")

Is there a function that will convert them to numbers?

Thank you so much

Sharif Amlani
  • 1,138
  • 1
  • 11
  • 25

4 Answers4

26

You can use match() with the built-in variable month.name.

match(months, month.name)
[1] 3 4 5 6 7 8 9

Or convert your months variable to a factor and then an integer:

as.integer(factor(months, levels = month.name))
Ritchie Sacramento
  • 29,890
  • 4
  • 48
  • 56
1
months = 1:12
names(months) = month.name
months['March']

OUTPUT

March 
    3 
Sreeja
  • 11
  • 2
1

Here is a tidyverse method to rename Months

df %>%
mutate(month = recode(month,
  Jan = 1,
  Feb = 2,
  Mar = 3,
  Apr = 4,
  May = 5,
  Jun = 6,
  Jul = 7,
  Aug = 8,
  Sep = 9,
  Oct = 10,
  Nov = 11,
  Dec = 12
))
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Sana
  • 65
  • 6
0

An alternative is to link month numbers and names via a named vector

months <- c("March",     "April",     "May",       "June",      "July",  "August",  "September")
x <- setNames(1:12, month.name)
unname(x[months] )
Tony Ladson
  • 3,539
  • 1
  • 23
  • 30