0

I have the following Df in R.

DF<-

Month      Count     Group
Dec-20     12        A2
Feb-21     30        R5
Mar-21     43        R5
Jan-21     90        B1 
Total      175       -

The Month are jumbled in the above dataframe, I need to make them in Descending order.

Required Df<-

Month      Count     Group
Mar-21     43        R5
Feb-21     30        R5
Jan-21     90        B1
Dec-20     12        A2 
Total      175       -
user9211845
  • 131
  • 1
  • 12

1 Answers1

2

You can use zoo::as.yearmon to convert the character values of month to yearmon class which can be arranged.

library(dplyr)
df %>% arrange(desc(zoo::as.yearmon(Month, '%b-%y')))

#   Month Count Group
#1 Mar-21    43    R5
#2 Feb-21    30    R5
#3 Jan-21    90    B1
#4 Dec-20    12    A2
#5  Total   175     -

In base R, create a date object and then use order.

df[order(as.Date(paste0(df$Month, '-1'), '%b-%y-%d'), decreasing = TRUE), ]

data

df <- structure(list(Month = c("Dec-20", "Feb-21", "Mar-21", "Jan-21", 
"Total"), Count = c(12L, 30L, 43L, 90L, 175L), Group = c("A2", 
"R5", "R5", "B1", "-")), class = "data.frame", row.names = c(NA, -5L))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213