Search code examples
rrefactoringrecode

Recode month factor


I have a dataset with like this:

age month
5    apr
6    jun
7    dec

When i write :

str(data$month)

I have,

Factor w/ 10 levels "apr","aug","dec",..: 7 7 7 7 7 7 7 7 7 7 ...

And

levels(data$month)
 [1] "apr" "aug" "dec" "jul" "jun" "mar" "may" "nov" "oct" "sep"

I would like to recode factor to month real month. I tried with:

    month<-c("Jan","Feb","Mar",
         "Apr","May","Jun",
         "Jul","Aug","Sep",
         "Oct","Nov","Dec")

data$month<-month[data$month]
data$month<-factor(data$month,levels=month.abb)

But when i see my data, may month is equal to jul. How can i do it?

thanks

thanks to @sotos it's works.

 library(stringr)
data$month<-str_to_title(data$month)
data$month<-factor(data$month,levels=month.abb)

Solution

  • It seems that you only need to convert the first letter to upper. There is a function str_to_title in stringr package that does that, i.e.

    library(stringr)
    str_to_title(c('may', 'jun', 'jul'))
    #[1] "May" "Jun" "Jul"