I want to sort month names. When I use the strptime
function it returns an error as the attribute values only contains month names. When I use the sort
function, the months are sorted alphabetically.
Asked
Active
Viewed 3.7k times
2 Answers
35
You could always convert your data to a factor. For example, suppose we have
x = c("January", "February", "March", "January")
then to convert to a factor, we have:
x_fac = factor(x, levels = month.name)
which on sorting gives:
R> sort(x_fac)
[1] January January February March
12 Levels: January February March April May June July August ... December

csgillespie
- 59,189
- 14
- 150
- 185
-
5Constants `month.name` and `month.abb` are useful in this regard so you don't need to type out the month names etc. Only useful for English month names and abbreviations though. – Gavin Simpson Mar 19 '12 at 12:10
-
2also, be careful with "Feburary" -- you're unlikely (I hope) to find it in the real data. Maybe that was part of the reason for @GavinSimpson's suggestion – Ben Bolker Mar 19 '12 at 12:20
-
1Thanks @GavinSimpson I didn't know about `month.name` – csgillespie Mar 19 '12 at 13:04
4
This is crude but if you wanted to make a function to sort or order rows by a month this would work:
sort.month <- function(x, dataframe = NULL){
y <- data.frame(m1 = month.name, m2 = month.abb, n = 1:12)
z <- if(max(nchar(x)) == 3) match(x, y[, 'm2']) else match(x, y[, 'm1'])
x <- if(is.null(dataframe)) x else dataframe
h <- data.frame(z, x)
h[order(z), ][, -1]
}
#examples
x <- sample(month.name, 20, r=T)
a<-data.frame(y= x, k =1:20, w=letters[1:20])
sort.month(a$y, a)
sort.month(a$y)

Tyler Rinker
- 108,132
- 65
- 322
- 519
-
I use this type of sorting a lot inside the custom functions I create - so I prefer this approach over the minimalist or standard approach posted by @csgillespie (i.e. my vote goes here). – SilSur Oct 06 '21 at 09:59
-
@SilSur at first I rejected the edit you suggested, but after considering more your suggestion was safe to assume internally. I manually edited the post to match your suggested edits as it was too late once I rejected it. – Tyler Rinker Oct 06 '21 at 13:18
-
-
Sorry no :-( I am the worst. I got this new power to approve edits and screwed it up my very first time. With great power comes great responsibility. – Tyler Rinker Oct 06 '21 at 17:48