Search code examples
datetimerecode

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


Solution

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