Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting months in R

Tags:

date

r

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.

like image 985
shridatt Avatar asked Mar 19 '12 11:03

shridatt


People also ask

How to sort dates in a dataframe in R?

Here order() function is used to sort the dataframe by R using order() function based on the date column, we have to convert the date column to date with the format, this will sort in ascending order.


1 Answers

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
like image 112
csgillespie Avatar answered Sep 27 '22 19:09

csgillespie