2

I am having a vector

monthData <- c("April", "June", "May", "August","July","September","December","November","October")

Is it possible to sort the vector in the chronological order of month name?

Thanks in advance

3 Answers 3

5

You can just use the built in month.name.

monthData[order(match(monthData, month.name))]
#> [1] "April"     "May"       "June"      "July"      "August"    "September"
#> [7] "October"   "November"  "December"
4

You could transform the vector to a factorized vector:

fact_monthData<-factor(monthData, levels=month.name)

Then you can sort the vector by:

sort(fact_monthData)
1

You could try sort on another vector consisting of full dates, in the same year, with the various month components:

dates <- as.Date(paste0("2020-", monthData, "-01"), format="%Y-%b-%d")
monthData[order(dates)]

[1] "April"     "May"       "June"      "July"      "August"    "September"
[7] "October"   "November"  "December" 

Data:

monthData <- c("April", "June", "May", "August", "July", "September", "December",
               "November","October")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.