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"
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.