Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort the month_year column as chronological order using R

i am trying show Mar ’21 as first and then go chronologically down from there

  x =  c("Dec-2020", "Nov-2020", "Oct-2020", "Sep-2020", "Aug-2020", 
    "Jul-2020", "Jun-2020", "May-2020", "Apr-2020", "Mar-2021", "Feb-2021", 
    "Jan-2021")

i tried to sort the variable but still i am not getting the expected order

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Convert to yearmon class in which case they sort chronologically. At the end we convert back to character. Omit the last leg of the pipeline if leaving it as yearmon is ok.

library(zoo)

x |>
  as.yearmon("%b-%Y") |>
  sort(decreasing = TRUE) |>
  format("%b-%Y")
##  [1] "Mar-2021" "Feb-2021" "Jan-2021" "Dec-2020" "Nov-2020" "Oct-2020"
##  [7] "Sep-2020" "Aug-2020" "Jul-2020" "Jun-2020" "May-2020" "Apr-2020"

Alternately write it like this:

format(sort(as.yearmon(x, "%b-%Y"), decreasing = TRUE), "%b-%Y")

or like this:

x[order(as.yearmon(x, "%b-%Y"), decreasing = TRUE)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading