1

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

     emp.data <- data.frame(
  emp_id = c (1:12), 
  emp_name = c("Rick","Dan","Michelle","Ryan","Gary","aa","bb","cc","dd","ee","qq","ww"),
  m_year =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

emp.data$m_year = emp.data$m_year[order(as.yearmon(emp.data$m_year, "%b-%Y"), decreasing = TRUE)]
Nazima
  • 93
  • 7

1 Answers1

1

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)]
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341