Sharif Amlani
Sharif Amlani

Reputation: 1278

Convert month names to numbers in r

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

Upvotes: 12

Views: 26179

Answers (4)

Sana
Sana

Reputation: 87

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
))

Upvotes: 3

Sreeja
Sreeja

Reputation: 11

months = 1:12
names(months) = month.name
months['March']

OUTPUT

March 
    3 

Upvotes: 1

Tony Ladson
Tony Ladson

Reputation: 3639

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] )

Upvotes: 0

lroha
lroha

Reputation: 34301

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))

Upvotes: 28

Related Questions